PYTHON:列表理解中的多个条件-匹配字符串
我有: 我的愿望输出是包含匹配器中字符串的字符串列表:PYTHON:列表理解中的多个条件-匹配字符串,python,string,list-comprehension,Python,String,List Comprehension,我有: 我的愿望输出是包含匹配器中字符串的字符串列表: mylist = ['person1 has apples', 'oranges and apples', 'person2 has oranges'] matchers = ['person1','person2'] 我已经成功地从匹配列表中显式写出了每个项目,但是实际数据比这个例子要大得多,所以我正在寻找更好的方法来实现输出 这项工作: output = ['person1 has apples', 'person2 has ora
mylist = ['person1 has apples', 'oranges and apples', 'person2 has oranges']
matchers = ['person1','person2']
我已经成功地从匹配列表中显式写出了每个项目,但是实际数据比这个例子要大得多,所以我正在寻找更好的方法来实现输出
这项工作:
output = ['person1 has apples', 'person2 has oranges']
但它需要明确列出matchers中的每一项
我试过这个:
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)]
但是,它仅在字符串列表中没有匹配项时生成错误消息。当mylist中有matchers中的匹配项时,代码就会工作。不知道为什么
**编辑-拼写错误更正。产生错误的代码中没有输入错误**
**EDIT2-代码正确,匹配者列表中有一个NaN** 你有一个打字错误;您可能已经在前面为x指定了一个浮点,并且
'in <string>' requires string as left operand, not float
指的是它
也许名称更明确一些:
matching = [s for s in mylist if any(x in s for xs 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)
这个怎么样:
matching=[s代表mylist中的s,如果anym代表matchers中的m]@AKX的回答表明问题只是一个输入错误;键入x而不是xs将得到正确的输出。谢谢您的评论。我现在已经纠正了错误-它只是在文章中,而不是在我的原始代码中!我现在还向帖子中添加了这样一个信息:当有匹配项时,代码可以工作,但当没有匹配项时,它会抛出一个错误。@Aleksnadra我添加了一个示例。对于空mylist和空matchers,它可以正常工作。你有什么问题?我发现了一个问题,在我长长的匹配者名单上有一个nan。。感谢您的帮助,代码运行良好!很高兴你发现了这个问题!谢谢你的评论。这正是我尝试过的,但它只有在有匹配的情况下才起作用。当没有匹配项时,它会抛出一个错误。
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']