问题如下:例如:
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
所以,我需要从字典“d”的键中包含列表“lst”中的所有元素,而没有子字符串匹配,因为如果我执行“print d [i]”,我得到一个错误。
答案 0 :(得分:3)
>>> lst = ['2456', '1871', '187']
>>> d = {
'1871': '1',
'2456': '0',
}
>>> [x for x in lst if x in d]
['2456', '1871']
答案 1 :(得分:1)
这一行应该完成这项工作:
l=[e for e in d if e in lst]
包含您的数据:
In [5]: l=[e for e in d if e in lst]
In [6]: l
Out[7]: ['2456', '1871']
答案 2 :(得分:0)
使用sets
:
lst = ['2456', '1871', '187']
d = {'1871': '1', '2456': '0'}
print(set(lst) & set(d.keys())) # prints '{'2456', '1871'}'
答案 3 :(得分:0)
>>> for i in li:
if i in d:
print "{0} => {1}".format(i,d[i])
2456 => 0
1871 => 1
在列表理解中:
>>> [i for i in li if i in d]
['2456', '1871']