0

例如,问题如下:

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]”,我会得到一个错误。

4

4 回答 4

3
>>> lst = ['2456', '1871', '187']
>>> d = {
    '1871': '1',
    '2456': '0',
}
>>> [x for x in lst if x in d]
['2456', '1871']
于 2013-04-23T08:53:20.603 回答
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']
于 2013-04-23T08:58:09.887 回答
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']
于 2013-04-23T08:57:04.920 回答
0

使用sets

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

print(set(lst) & set(d.keys())) # prints '{'2456', '1871'}'
于 2013-04-23T08:53:30.033 回答