我有一个列表作为元组的输入,其中原点是第一个对象而邻居是元组的第二个对象。 例如:
inp : lst = [('a','b'),('b','a'),('c',''),('a','c')]
out : {'a': ('a', ['b', 'c']), 'b': ('b', ['a']), 'c': ('c', [])}
首先我试图将名单列入dictonary, 像这样
dictonary = dict(lst)
但我收到错误说
dictionary update sequence element #0 has length 1; 2 is required
答案 0 :(得分:0)
这是我如何做到的,获得你想要的结果,你可以将两个操作混合到同一个循环中,从中创建一个函数等,玩得开心!没有Python写的一个衬衫功夫为初学者友好!
>>> lst = [('a','b'),('b','a'),('c',''),('a','c')]
>>> out = {}
>>> for pair in lst:
... if pair[0] not in out:
... out[pair[0]] = (pair[0], [])
...
>>> out
{'a': ('a', []), 'c': ('c', []), 'b': ('b', [])}
>>> for pair in lst:
... out[pair[0]][1].append(pair[1])
...
>>> out
{'a': ('a', ['b', 'c']), 'c': ('c', ['']), 'b': ('b', ['a'])}
答案 1 :(得分:0)
最简单的可能是在try / except块中:
lst = [('a','b'),('b','a'),('c',''),('a','c')]
out = dict()
for k, v in lst:
try:
if v != '':
out[k][1].append(v)
else:
out[k][1].append([])
except KeyError:
if v != '':
out[k] = (k, [v])
else:
out[k] = (k, [])
print out
给出了:
{'a': ('a', ['b', 'c']), 'b': ('b', ['a']), 'c': ('c', [])}
答案 2 :(得分:0)
在此提及lst = [('a','b'),('b','a'),('c',''),('a','c')]
d = {}
for first, second in lst:
tup = d.setdefault(first, (first, []))
if second and second not in tup[1]:
tup[1].append(second)
addItem(new Item(ID,Name,Detail,Image1,Image2));