首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Python中将过滤后的字符串追加到新列表中?

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

Stack Overflow用户
提问于 2019-08-02 08:26:55
回答 5查看 1.4K关注 0票数 3

我想在从旧列表中筛选出来的新列表中添加一个字符串。

到目前为止我尝试过的是:

代码语言:javascript
复制
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)

我的预期产出是:

代码语言:javascript
复制
['thai01', 'thai02', 'thai03']
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2019-08-02 08:29:13

您可以使用列表理解:

代码语言:javascript
复制
languages = ['thai01', 'thai02', 'thai03', 'jap01', 'jap02', 'jap03']
thai = [x for x in languages if 'thai' in x]
print(thai)

产出:

代码语言:javascript
复制
['thai01', 'thai02', 'thai03']

若要帮助您理解这个oneliner的逻辑,请参阅以下基于代码的示例:

代码语言:javascript
复制
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'是否发生(在本例中是在函数的帮助下),它的逻辑与上面的列表理解相同(尽管对于第一个示例您甚至不需要这个函数)。您还可以结合您的功能使用列表理解:

代码语言:javascript
复制
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']
票数 3
EN

Stack Overflow用户

发布于 2019-08-02 08:36:13

您还可以在lambda函数中使用filter

代码语言:javascript
复制
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']

或列表理解

代码语言:javascript
复制
thai = [y for y in languages if 'tha' in y]
票数 2
EN

Stack Overflow用户

发布于 2019-08-02 08:29:31

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

代码语言:javascript
复制
thai.extend(filter(filter_str, languages))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57322593

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档