对于字典值中的每个项目,使用len> 1,我在len == 1的另一个字典值中搜索该项目。如果我在len == 1的另一个字典值中找到该项目,我想从较长的值中删除它。例如:
d = {
'key1' : ['one', 'two', 'three'],
'key2' : ['one'],
'key3' : ['two', 'three'],
}
应该返回
{
'key1' : ['two', 'three'],
'key2' : ['one'],
'key3' : ['two', 'three'],
}
我目前的代码
allvals = match.values()
for k, v in match.iteritems():
dontuse = []
newval = []
for i in v:
for x in allvals:
if x == v:
pass
elif i in x:
if len(x) == 1:
dontuse.append(i)
for i in v:
if i in dontuse:
pass
else:
newval.append(i)
match[k] = list(set(newval))
然而,这是处理时间的极端瓶颈。任何帮助将不胜感激,谢谢!
答案 0 :(得分:1)
您只需要遍历字典一次即可找到ali_sms.ali_send_code_sms
。然后你只需复制字典,根据需要将列表条目留给长度大于1的列表。一些列表和字典理解提供了一个简洁的解决方案:
dontuse
此外,最好不要将dontuse = {s for val in match.values() for s in val if len(val) == 1}
match = {key: [s for s in val if len(val) == 1 or not s in dontuse] for key, val in match.iteritems()}
或任何其他内置内容用作变量名称。
答案 1 :(得分:1)
要解释你想要做的事情有点困难,但我相信你可以把它分成两步:
这两个都可以用理解(set,dict)完成,例如:
>>> d = { 'key1' : ['one', 'two', 'three'], 'key2' : ['one'], 'key3' : ['two', 'three']}
>>> r = {v[0] for k, v in d.items() if len(v) == 1}
>>> {k: [v for v in vs if v not in r] if len(vs) > 1 else vs for k, vs in d.items()}
{'key1': ['two', 'three'], 'key2': ['one'], 'key3': ['two', 'three']}
答案 2 :(得分:1)
我想到的第一件事就是使用套装:
match = { 1 : ['one', 'two', 'three'], 2 : ['one'], 3 : ['two', 'three'] }
singles=set()
for v in match.values():
if len(v)==1:
singles.add(v[0])
for k, v in match.iteritems():
if len(v)>1:
for el in v:
if el in singles:
match[k].remove(el)
match
{1: ['two', 'three'], 2: ['one'], 3: ['two', 'three']}