I've written some overly complex lambdas to do this, but I want to simplify. 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"]
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 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).
And you can generate a set
directly (although you don't need to unless you have duplicates in 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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.