PYTHON:列表理解中的多个条件-匹配的字符串

问题描述 投票:0回答:2

我有:

mylist = ['person1 has apples', 'oranges and apples', 'person2 has oranges']

matchers = ['person1','person2']

我的愿望输出是一个字符串列表,其中包含匹配器中的字符串:

output = ['person1 has apples', 'person2 has oranges']

我设法实现了从匹配列表中明确写出每个项目的实现,但是实际数据比本示例大得多,因此我正在寻找实现输出的更好方法。

此作品:

matching = [s for s in mylist if "person1" in s or "person2" in s]

但是它需要明确列出匹配器中的每个项目。

我已经尝试过:

matching = [s for s in mylist if any(x in s for x in matchers)]

但是我收到以下错误消息:

'in <string>' requires string as left operand, not float

但是,仅当字符串列表中没有匹配项时,它才会生成错误消息。如果mylist中的匹配项有匹配项,则代码有效。不知道为什么!

**编辑-错字更正。代码中没有拼写错误,导致产生错误**

python string list-comprehension
2个回答
1
投票

您有错字;您可能之前已将浮点数分配给x,并且

matching = [s for s in mylist if any(x in s for xs in matchers)]

指它。

也许用名称更明确:

matching = [text for text in mylist if any((matcher in text) for matcher in matchers)]

示例

mylist = [
    "person1 has apples",
    "oranges and apples",
    "person2 has oranges",
]
matchers = ["person1", "person2"]
matching = [
    text
    for text in mylist
    if any(matcher in text for matcher in matchers)
]
print(mylist)
print(matchers)
print(matching)

输出

['person1 has apples', 'oranges and apples', 'person2 has oranges']
['person1', 'person2']
['person1 has apples', 'person2 has oranges']

0
投票

如何:matching = [s for s in mylist if any(m in s for m in matchers)]

© www.soinside.com 2019 - 2024. All rights reserved.