Question

a_lst = ['chair','gum','food','pizza']
letter = 'x'
for word in a_lst:
  if letter not in word:
    print ('no',letter)

  elif letter in word:
    print ('yes',letter)   

Output:

no x
no x
no x
no x

Is there a way i can iterate though each item in "a_lst", check if each item has letter 'x'. if no item has letter 'x' print 'no x' just Once. If a word contains letter 'x', print 'yes x' just Once.

I think my logic is flawed somewhere.

Any suggestions?

Thanks

Était-ce utile?

La solution

You could do this:

letter = 'x'
result = [a for a in a_lst if letter in a]
if result:
    print('yes', letter)
else:
    print('no', letter)

Explanation:
result will be [] if none of the words in a_lst has the letter. When you do a if result on an empty list, it returns False, otherwise it returns True. The conditional statements check and print the output statement accordingly.

Another way to do it in python is to use the filter function:

if filter(lambda x: letter in x, a_lst):
    print('yes', letter)
else:
    print('no', letter)

Yet another way to do it is to use any:

if any(letter in word for word in a_list):
    print('yes', letter)
else:
    print('no', letter)

any(letter in word for word in a_list) returns True if any of the words have the letter.

Autres conseils

You can use the any function!

if any(letter in word for word in a_lst):
    print('yes', letter)
else:
    print('no', letter)

Have you tried something like this:

a = ['chair', 'gum', 'food', 'pizza']

letter = 'a'

result = 'no ' + letter
k = 0

for i in a:

    if letter in a[k]:
        print(a[k])
        result = 'yes ' + letter

    k += 1

print(result)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top