[英]Python: Replace for loops with list comprehension
I'm fairly new at python and list comprehensions are not my strong point.我是 python 的新手,列表理解不是我的强项。 However, I need some help reducing a nested for loop into a single statement like a list comprehension.但是,我需要一些帮助,将嵌套的 for 循环减少为单个语句,如列表推导式。 What I have is:我所拥有的是:
source_file_list = ['file1', 'file2', 'file3', 'file4', 'file5', 'file6']
test_file_list = ['file1', 'file3', 'file5']
for i in range(len(source_file_list)):
for j in range(len(test_file_list)):
if test_file_list[j] in source_file_list[i]:
file_match_list.append(source_file_list[i])
break
Any help is appreciated, I'm trying to get rid of the "append"任何帮助表示赞赏,我正在尝试摆脱“附加”
Use set intersections:使用集合交点:
source_file_list = ['file1', 'file2', 'file3', 'file4', 'file5', 'file6']
test_file_list = ['file1', 'file3', 'file5']
file_match_list = set(test_file_list).intersection(source_file_list)
print(file_match_list) # {'file5', 'file1', 'file3'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.