繁体   English   中英

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

[英]PYTHON: Multiple conditions in list comprehensions - matching strings

我有:

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

matchers = ['person1','person2']

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

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

我已经设法从匹配列表中明确地写出每个项目,但实际数据比这个例子大得多,所以我正在寻找更好的方法来实现 output。

这有效:

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 中的匹配器匹配时 - 代码有效。 不知道为什么!

** 编辑 - 错字已更正。 产生错误的代码中没有错字**

** EDIT2 - 代码正确,匹配器列表中有一个 NaN! **

你有一个错字; 您之前可能已经为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']

怎么样: matching = [s for s in mylist if any(m in s for m in matchers)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM