我想在从旧列表中筛选出来的新列表中添加一个字符串。
到目前为止我尝试过的是:
languages = ['thai01', 'thai02', 'thai03', 'jap01', 'jap02', 'jap03']
thai = []
japanese = []
def filter_str(lang):
if 'tha' in lang:
return True
else:
return False
filter_lang = filter(filter_str, languages)
thai = thai.append(filter_lang)
print(thai)我的预期产出是:
['thai01', 'thai02', 'thai03']发布于 2019-08-02 08:29:13
您可以使用列表理解:
languages = ['thai01', 'thai02', 'thai03', 'jap01', 'jap02', 'jap03']
thai = [x for x in languages if 'thai' in x]
print(thai)产出:
['thai01', 'thai02', 'thai03']若要帮助您理解这个oneliner的逻辑,请参阅以下基于代码的示例:
languages = ['thai01', 'thai02', 'thai03', 'jap01', 'jap02', 'jap03']
thai = []
def filter_str(lang):
if 'tha' in lang:
return True
else:
return False
for x in languages:
if filter_str(x):
thai.append(x)
print(thai)
# ['thai01', 'thai02', 'thai03']for循环检查字符串'tha'是否发生(在本例中是在函数的帮助下),它的逻辑与上面的列表理解相同(尽管对于第一个示例您甚至不需要这个函数)。您还可以结合您的功能使用列表理解:
languages = ['thai01', 'thai02', 'thai03', 'jap01', 'jap02', 'jap03']
def filter_str(lang):
if 'tha' in lang:
return True
else:
return False
thai = [x for x in languages if filter_str(x)]
print(thai)
# ['thai01', 'thai02', 'thai03']发布于 2019-08-02 08:36:13
您还可以在lambda函数中使用filter。
languages = ['thai01', 'thai02', 'thai03', 'jap01', 'jap02', 'jap03']
thai = list(filter(filter_str,languages)) # or thai = list(filter(lambda x:'thai' in x,languages))
print(thai) #['thai01', 'thai02', 'thai03']或列表理解
thai = [y for y in languages if 'tha' in y]发布于 2019-08-02 08:29:31
执行下一步,而不是使用thai.append
thai.extend(filter(filter_str, languages))https://stackoverflow.com/questions/57322593
复制相似问题