如何在Python中将过滤后的字符串附加到新列表中?

2024-10-03 15:22:11 发布

您现在位置: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 = filter(filter_str, languages)
thai = thai.append(filter_lang)

print(thai)

我的预期产出是:

['thai01', 'thai02', 'thai03']

Tags: 字符串列表langreturnfilterlanguagesstrjapanese
3条回答

执行下一步而不是使用thai.append

thai.extend(filter(filter_str, languages))

您可以使用列表:

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']

也可以将filter与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]

相关问题 更多 >