简体   繁体   中英

How to return list of strings if a string in a list contains another string python

If i have a list of strings, I want to return the strings in that list that are contained in the strings of that list. For instance: ["red", "blue", "loss", "boss", "sloss"] would return ["loss"]. I have been trying to do this only using lambdas + filter and no loops/comprehensions but can't seem to figure out why my solution isnt working:

list(filter(lambda x: x if x in stringlist else "", stringlist))

You are checking if the strings are in the lsit of string, not if the strings are substrings of one of the strings.

Try:

list(filter(lambda x: any(x in y and x != y for y in stringlist), stringlist))

It checks if the strings are stricly contained in one of the other string ( x in y and x != y ) so it will not match equal strings in the list .

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.

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