【发布时间】:2019-09-03 16:48:22
【问题描述】:
所以我有 2 个列表:
list1 = ['abc', 'efg', 'hijk'] #list of strings
list2 = ['lmno', 'pqrs'] #also a list of strings
然后我有一个相当大的字典 通常,列表中只有大约 100 个键和几十万个字符串值
d = {'abc': ['lmno'], 'efg': ['lmno', 'pqrs']}
所以我需要遍历list1的每一项和list2的每一项:
示例:
for i1 in list1:
for i2 in list2:
print(i1, i2)
然后将数据与字典进行比较:
for i1 in list1:
for i2 in list2:
if i1.lower() in d:
if i2 in d[i1.lower()]:
continue #ignore
else:
#process data
目前,我的代码和上面一样,但是当字典很大时它很慢 有更快的方法吗?
for i1 in list1:
for i2 in list2:
if i1.lower() in d:
if i2 in d[i1.lower()]:
continue #ignore
else:
#process data
【问题讨论】:
-
使用集合的字典而不是列表的字典。
-
在
#process data你也需要钥匙吗?还是只有价值观? -
如果 list1 中的至少一个字符串是您的 dict 中的键,您想处理数据吗?并且列表 2 中的至少一个字符串应该在 dict[key_lsit1] 中?因为目前你正在做
process data这么多次,因为 list2 中的元素在 dict[key_lsit1] 中,似乎效率低下
标签: python python-3.x list dictionary