问题描述
对于给定列表:
list = ['enwiki-latest-stub-Meta-history.xml.gz','enwiki-latest-stub-Meta-history.xml.gz-RSS.xml','enwiki-latest-stub-Meta-history1.xml.gz','enwiki-latest-stub-Meta-history1.xml.gz-RSS.xml','enwiki-latest-stub-Meta-history10.xml.gz','enwiki-latest-stub-Meta-history10.xml.gz-RSS.xml','enwiki-latest-stub-Meta-history11.xml.gz','enwiki-latest-stub-Meta-history11.xml.gz-RSS.xml','enwiki-latest-stub-Meta-history12.xml.gz','enwiki-latest-stub-Meta-history12.xml.gz-RSS.xml']
我尝试了这些:
generated_list = [l for l in list if re.compile(r".gz$") in l]
generated_list = [file.endswith('.gz') for file in files]
generated_list = [file for file in files if '.gz' in file]
以上方法似乎都不起作用,第二种方法却有效,但只能产生布尔值。
解决方法
解决此问题的正确方法是学习列表理解的工作原理。
generated_list = [file for file in files if file.endswith('.gz')]
,
const