如何在Python中将经过筛选的字符串添加到新列表中?

3
我希望将一个字符串附加到从旧列表过滤出来的新列表中。
到目前为止,我尝试过以下方法:
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']
6个回答

3
你可以使用列表推导式:
```Python ```
你可以使用列表推导式:
languages = ['thai01', 'thai02', 'thai03', 'jap01', 'jap02', 'jap03']
thai = [x for x in languages if 'thai' in x]
print(thai)

输出:

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

为了帮助您理解这个单行代码的逻辑,请参考以下基于您的代码的示例:

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

1
谢谢,我对列表推导有了更深入的理解。 - Teerapat

2
你可以使用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]

0

不要使用 thai.append,而是使用下一个操作:

thai.extend(filter(filter_str, languages))

0
  • startswith() 方法返回一个布尔值,如果一个字符串以指定的前缀(字符串)开头,则返回 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)

输出:

['thai01', 'thai02', 'thai03']
['jap01', 'jap02', 'jap03']

0
为什么不使用推导式?例如:
thai = [x for x in languages if filter_str(x)]

0

如果您喜欢函数式编程风格,可以使用operator.methodcaller()

from operator import methodcaller

languages = ['thai01', 'thai02', 'thai03', 'jap01', 'jap02', 'jap03']
thai = list(filter(methodcaller('startswith', 'tha'), languages))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接