Reputation: 486
I have a list of strings and a list of substrings. I want to generate a list of substrings not in the list of strings.
substring_list=["100", "101", "102", "104", "105"]
string_list=["101 foo", "102 bar", "103 baz", "104 lorem"]
I tried to do new_list = [s for s in substring_list if s not in [i for i in string_list]]
, but this doesn't work. I've also tried various uses of any()
but have had no luck.
I'd like to return new_list=["100", "105"]
.
Upvotes: 1
Views: 128
Reputation: 54223
Coming from a Ruby background and since Python has any
and all
, I looked for a none
function or method but was surprised to see it doesn't exist.
If you often use not any
or all not
, it could be interesting to define none()
:
def none(iterable):
for element in iterable:
if element:
return False
return True
substring_list = ["100", "101", "102", "104", "105"]
string_list = ["101 foo", "102 bar", "103 baz", "104 lorem"]
print([sub for sub in substring_list if none(sub in s for s in string_list)])
# ['100', '105']
It might lead to confusion with None
though. That's probably the reason why it doesn't exist.
Upvotes: 1
Reputation: 214957
You can try this:
[sub for sub in substring_list if all(sub not in s for s in string_list)]
# ['100', '105']
Or alternatively:
[sub for sub in substring_list if not any(sub in s for s in string_list)]
# ['100', '105']
Upvotes: 5
Reputation: 1
Code written returns all because "for i in string_list" creates a new set identical string_list array solve it is split handy split the organs to benefit string_list and then when you start i [0] you create similar string_list system but contains only numbers without letters
so
new_list = [s for s in substring_list if s not in [i.split()[0] for i in string_list]]
Upvotes: -1