Check if list item exists in row

I want to check if a string contains an item from a list:

l = ['S', 'R', 'D', 'W', 'V', 'Y', 'H', 'K', 'B', 'M']

s = 'YTG'

First decision:

for i in l:
    if i in s:
        print i

This seems ineffective. I tried the following code, but it gives me the last element of the list 'M'instead 'Y':

if any(i in s for i in l):
    print i

I was wondering what is the problem here?

Thank!

+4
source share
3 answers

any()creates Trueor False, and generator expression variables are not available outside the expression:

>>> l = ['S', 'R', 'D', 'W', 'V', 'Y', 'H', 'K', 'B', 'M']
>>> s = 'YTG'
>>> any(i in s for i in l)
True
>>> i
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'i' is not defined

Use the list to list all the matching letters:

matching = [i for i in l if i in s]
if matching:
    print matching

This keeps order in l; if the order in matchingdoesn't matter, you can just use the given intersections. I would make a lset here:

l = set(['S', 'R', 'D', 'W', 'V', 'Y', 'H', 'K', 'B', 'M'])  # Python 3 can use {...}
matching = l.intersection(s)
if matching:
    print matching

l , Python s.

+8

any , True False, .

, set :

l = ['S', 'R', 'D', 'W', 'V', 'Y', 'H', 'K', 'B', 'M']

s = set('YTG')
print(s.intersection(l))

{'Y'}.

+1

One liner:

set(list(s)).intersection(set(l))

{'Y'}

How @Martijn Pieters ♦ just comment:

set(s).intersection(l) will do the trick as shown in @ Jean-François Fabre's answer

+1
source

Source: https://habr.com/ru/post/1686046/


All Articles