Ad

Finding Substrings That Contain Each Other In Two Different Lists In Pytyhon

- 1 answer

Really basic question, but I couldn't find the way to properly achieve this.

I have two lists:

vowels = ['a', 'e', 'i', 'o', 'u']

and

usernames = ['example1', 'zzzzz23', 'eeeee43', 'llllll5', 'pppapp1', 'wwsd0']

I want, to extract from usernames all elements that don't have vowels in them.

I tried:

usernames_without_vowels = []
for username in usernames:
  if str(vowels) not in username:
    usernames_without_vowels.append(username)
  else: pass
print(usernames_without_vowels)

OUTPUT 1:

>> ['example1', 'zzzzz23', 'eeeee43', 'llllll5', 'pppapp1', 'wwsd0']

As you can see, it printed the whole usernames list, as it seems to not look for substrings too.

I then tried zipping both lists as it follows:

usernames_without_vowels = []
for username,vowel in zip(usernames,vowels):
  if str(vowels) not in str(username):
    usernames_without_vowels.append(username)
  else: pass
print(usernames_without_vowels)

but, then again: OUTPUT 2:

>> ['example1', 'zzzzz23', 'eeeee43', 'llllll5', 'pppapp1']

it printed the whole usernames list EXCEPT the last value: wwsd0.

Also tried:

usernames_without_vowels = [username for username in usernames if str(vowels) not in username]
print(usernames_without_vowels)

and OUTPUT 3:>> ['example1', 'zzzzz23', 'eeeee43', 'llllll5', 'pppapp1', 'wwsd0']

I want to get all usernames in which EACH STRING of vowels is NOT present, but can't find a way.

EXPECTED OUTPUT:

>> ['zzzzz23', 'llllll5', 'wwsd0']

SOLUTION

Following @Helios solution, it was accomplished by:

username_without_vowels = [u for u in usernames if not any([v in u for v in vowels])]

Simple, and (very) effective.

Thank you for all the help!

Ad

Answer

[u for u in usernames if not any(v in u for v in vowels)]

EDIT:

Updated to include @cglacet comment

Ad
source: stackoverflow.com
Ad