I have the following code:
mystring = ["reddit", "google"]
mylist = ["a", "b", "c", "d"]
for mystr in mystring:
if any(x not in mystr for x in mylist):
print mystr
I'm expecting that this should return only google. But for some reason it returns both reddit and google.
Your use of any
and not in
contradicts itself. You want to check either for all
like this:
if all(x not in mystr for x in mylist):
print mystr
Or just check for not any
(which is more readable in my opinion):
if not any(x in mystr for x in mylist):
print mystr
Both of these versions can be a one-liner by the way (instead of your loop), if you use list comprehension (but that is just a matter of taste, or if you prefer to print out one line of results instead of one line for every result):
mystring = ["reddit", "google"]
mylist = ["a", "b", "c", "d"]
print [s for s in mystring if not any(x in s for x in mylist)]
if you don't want any of these letters to appear in your strings, then you should use:
all(x not in mystr for x in mylist)
and not any
:
mystring = ["reddit", "google"]
mylist = ["a", "b", "c", "d"]
for mystr in mystring:
if all(x not in mystr for x in mylist):
print mystr
prints only
google
To ensure the input string does not contain any char from the list, your condition should be:
...
if not any(x in mystr for x in mylist):
Here is your code working, just with different variable names:
words = ["reddit", "google"]
chars = ["a", "b", "c", "d"]
for word in words:
print(word,":",[char not in word for char in chars]) #explanation help
if all(char not in word for char in chars):
print("none of the characters is contained in",word)
Its output:
reddit : [True, True, True, False]
google : [True, True, True, True]
none of the characters is contained in google
As you see you only need to change any
to all
. This is because you want to test whether none of the characters is contained in the word, so whether all list elements as shown in the output are true, not just any of them.
Try this
s = ["reddit","google"]
l = ["a","b","c","d"]
for str in s:
if all(x not in str for x in l):
print(str)
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.