[英]Pythonic way to generate list of strings containing a fragment from another list?
I've written some overly complex lambdas to do this, but I want to simplify. 我已经写了一些过于复杂的lambda来做到这一点,但是我想简化一下。 I basically want a list of strings that contain one fragment from a list.
我基本上想要一个包含列表中一个片段的字符串列表。
Example: 例:
strings = ["asdf", "foo", "bar", "food"]
frags = ["foo", "ar"]
Would result in ["foo", "food", "bar"]
会导致
["foo", "food", "bar"]
Something like: [[s for s in string if f in s] for f in frags]
works in that it would make [["foo", "food"], ["bar"]]
, but I want a single list of that stuff, which I would then list(set()) to get unique items. 类似的东西:
[[s for s in string if f in s] for f in frags]
工作方式是使[["foo", "food"], ["bar"]]
但我只需要一个列表这些东西,然后我将列出(set())以获得唯一的物品。
>>> [s for s in strings if any(f in s for f in frags)]
['foo', 'bar', 'food']
The advantage of this approach is that any()
short-circuits, aborting as soon as it finds a match (which also means that you won't get duplicate items if more than one fragment happens to match a string). 这种方法的优点是
any()
短路,一旦找到匹配项就会中止(这也意味着,如果有多个片段匹配一个字符串,您将不会得到重复的项)。
And you can generate a set
directly (although you don't need to unless you have duplicates in strings
): 而且,您可以直接生成一个
set
(尽管您不需要,除非您在strings
有重复项):
>>> {s for s in strings if any(f in s for f in frags)}
{'bar', 'food', 'foo'}
您可以轻松地将它们组合:
[s for s in strings for f in frags if f in s]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.