如何在Python中将过滤后的字符串附加到新列表中?
我想在从旧列表中筛选出来的新列表中附加一个字符串 到目前为止,我所尝试的:如何在Python中将过滤后的字符串附加到新列表中?,python,Python,我想在从旧列表中筛选出来的新列表中附加一个字符串 到目前为止,我所尝试的: languages = ['thai01', 'thai02', 'thai03', 'jap01', 'jap02', 'jap03'] thai = [] japanese = [] def filter_str(lang): if 'tha' in lang: return True else: return False filter_lang = filt
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']
您可以使用列表:
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']
检查字符串'tha'
是否发生的for
循环(在本例中,借助于函数),与上面的列表理解逻辑相同(尽管在第一个示例中,您甚至不需要函数)。您还可以将列表理解与功能结合使用:
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']
执行下一步操作,而不是使用泰国语。追加:
thai.extend(过滤器(过滤器,语言))
- 如果字符串以指定的前缀(字符串)开头,则方法返回True。如果不是,则返回False
languages = ['thai01', 'thai02', 'thai03', 'jap01', 'jap02', 'jap03']
thai = []
japanese = []
for x in languages:
if x.startswith("tha"):
thai.append(x)
else:
japanese.append(x)
print(thai)
print(japanese)
O/p:
['thai01', 'thai02', 'thai03']
['jap01', 'jap02', 'jap03']
为什么不做一个理解?e、 g
thai = [x for x in languages if filter_str(x)]
您还可以将
过滤器
与lambda函数一起使用
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]
如果您喜欢功能性风格,可以使用:
谢谢,我对列表理解有了更多的了解。
from operator import methodcaller
languages = ['thai01', 'thai02', 'thai03', 'jap01', 'jap02', 'jap03']
thai = list(filter(methodcaller('startswith', 'tha'), languages))