BlackHat
BlackHat

Reputation: 755

For loop with If not working as expected

I have this little piece of code I'm working with. I'm a novice so kindly pardon my ignorance.

The intended logic is:

for a value in list y, find any match in list s and print out the value in list s (not list y). My current code prints out list y but I actually want list s.

Here is my current code:

y = ['a','m','j']
s = ['lumberjack', 'banana split']

for x in s:
    if any(x in alpha for alpha in y):
           print x

I intend to print 'lumberjack' and 'banana split' but the code as is prints 'a' Please help :)

Thank you

Upvotes: 0

Views: 96

Answers (2)

JoeC
JoeC

Reputation: 1850

Printing "a" is correct, if you wanna print "lumberjack", append those characters to your alpha list (i.e. variable y)

y = 'albumjcker' # all characters inside "lumberjack"
s = 'lumberjack'

for x in s:
    if any(x in alpha for alpha in y):
           print x

should do the trick


Try:

y = ["a", "b", "c", "l"]
s = ["banana split", "lumberjack"]
for words in s:
    for char in y:
        if char in words:
            print (words)
            break

y = ["animal","zoo","potato"] 
s =  ["The animal farm on the left","I had potatoes for lunch"]
for words in s:
    for char in y:
        if char in words:
            print (words)
            break

The animal farm on the left
I had potatoes for lunch

Edit

y = ["animal","zoo","potato"] 
s =  ["The animal farm on the left","I had potatoes for lunch"]
s = list(set(s)) # But NOTE THAT this might change the order of your original list
for words in s:
    for char in y:
        if char in words:
            print (words)
            break

if order is important, then i guess you can only do

y = ["animal","zoo","potato"] 
s =  ["The animal farm on the left","I had potatoes for lunch"]

new = []
for x in s:
    if x not in new:
        new.append(x)
s = new

for words in s:
    for char in y:
        if char in words:
            print (words)
            break

Upvotes: 1

Ffisegydd
Ffisegydd

Reputation: 53668

In your for loop you were just printing the character that you were iterating over at the time, not the full string.

y = 'a'
s = 'lumberjack'

for x in s:
    if any(x in alpha for alpha in y):
       print s # Return 'lumberjack'

EDIT If you have a list of characters (as your comment suggested) then:

y = ['a', 'z', 'b']
s = 'lumberjack'

def check_chars(s, chars):
    for char in y:
        if char in s:
            print s
            break

for s in ['lumberjack','banana split']:
    check_chars(s,y)

This checks whether the string in y ('a') is a substring of s ('lumberjack'), it also breaks after you've printed so you don't possibly print multiple times.

Upvotes: 1

Related Questions