Python 在字典值中查找项目,在另一个长度为1的字典值中查找项目
对于len>1的字典值中的每个项,我将在len==1的另一个字典值中搜索该项。如果我在另一个len==1的字典值中找到该项,我想从较长的值中删除它。例如:Python 在字典值中查找项目,在另一个长度为1的字典值中查找项目,python,dictionary,Python,Dictionary,对于len>1的字典值中的每个项,我将在len==1的另一个字典值中搜索该项。如果我在另一个len==1的字典值中找到该项,我想从较长的值中删除它。例如: d = { 'key1' : ['one', 'two', 'three'], 'key2' : ['one'], 'key3' : ['two', 'three'], } 应该回来 { 'key1' : ['two', 'three'], 'key2' : ['one'], 'key3' : ['t
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))
然而,这是处理时间的一个极端瓶颈。任何帮助都将不胜感激,谢谢 您只需遍历字典一次即可找到
dontuse
。然后,您只需复制字典,根据需要为长度大于1的列表省略列表条目。几个列表和字典的理解给出了一个简洁的解决方案:
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()}
另外,最好不要使用
dict
或任何其他内置变量名。要解释您试图执行的操作有点困难,但我相信您可以将其分为两个步骤:
- 创建一组要删除的项
- 删除列表len>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']}
你的解决方案行得通吗?我的解决方案行得通,当使用一个大字典(可能有100000多个键)时,它的速度太慢了。在你的输出中,
dict[key2]
应该是['one']
还是[]
?dict[key2]应该是['one'],并且应该从dict[key1]中删除'one'更好地使用set()
对于dontuse
,集合中的查找是O(1)
vsO(n)
列表。感谢大家的帮助,我从来没有想过要先迭代一次才能找到dontuse。您的两种解决方案都是完美的。
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']}