簡體   English   中英

Python:用列表理解替換 for 循環

[英]Python: Replace for loops with list comprehension

我是 python 的新手,列表理解不是我的強項。 但是,我需要一些幫助,將嵌套的 for 循環減少為單個語句,如列表推導式。 我所擁有的是:

 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

任何幫助表示贊賞,我正在嘗試擺脫“附加”

使用集合交點:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM