简体   繁体   中英

Python check list items for a string

The problem is the following, for instance:

lst = ['2456', '1871', '187']

d = {
    '1871': '1',
    '2456': '0',
}

for i in lst:
    if any(i in x for x in d.keys()):
        print i

% python test.py
2456
1871
187

So, I need to get all the elements from the list "lst" that are contained in the keys of dictionary "d", without a substring match, cause if I do "print d[i]", I get an error.

>>> lst = ['2456', '1871', '187']
>>> d = {
    '1871': '1',
    '2456': '0',
}
>>> [x for x in lst if x in d]
['2456', '1871']

this line should do the job:

 l=[e for e in d if e in lst]

with your data:

In [5]: l=[e for e in d if e in lst]

In [6]: l
Out[7]: ['2456', '1871']

Using sets :

lst = ['2456', '1871', '187']
d = {'1871': '1', '2456': '0'}

print(set(lst) & set(d.keys())) # prints '{'2456', '1871'}'
>>> for i in li:
    if i in d:
        print "{0} => {1}".format(i,d[i])


2456 => 0
1871 => 1

In a list comprehension:

>>> [i for i in li if i in d]
['2456', '1871']

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM