I'm fairly new at python and list comprehensions are not my strong point. However, I need some help reducing a nested for loop into a single statement like a list comprehension. 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'}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.