我有一个这样的清单:
table=[{'device': 'a', 'iface': 'i1'}, {'device': 'a', 'iface': 'i2'}, {'device': 'a', 'iface': 'i4'}, {'device': 'b', 'iface': 'i5'}, {'device': 'a', 'iface': 'i3'}, {'device': 'b', 'iface': 'i7'}]
我想将该列表分组到这样的新列表中:
newtable=[{'device':'a','iface':['i1','i2','i4','i3']},{'device':'b','iface':['i5','i7']}]
我曾尝试使用collections模块中的defaultdict,但结果并非我的预期。 请帮我。提前致谢
这里我做了什么:
from collections import defaultdict
table=[{'device': 'a', 'iface': 'i1'}, {'device': 'a', 'iface': 'i2'}, {'device': 'a', 'iface': 'i4'}, {'device': 'b', 'iface': 'i5'}, {'device': 'a', 'iface': 'i3'}, {'device': 'b', 'iface': 'i7'}]
newtable=defaultdict(list)
for row in table:
newtable[row['device']].append(row['iface'])
newtable=list(newtable)
我从这里迷路了。 对不起我的英语。
答案 0 :(得分:3)
这是一种方法 - 只使用defaultdict
可能还不够。您可能需要进一步处理它(只需确保使用更好的变量名:)):
>>> from collections import defaultdict
>>> xx = defaultdict(list)
>>> table=[{'device': 'a', 'iface': 'i1'}, {'device': 'a', 'iface': 'i2'}, {'device': 'a', 'iface': 'i4'}, {'device': 'b', 'iface': 'i5'}, {'device': 'a', 'iface': 'i3'}, {'device': 'b', 'iface': 'i7'}]
>>> for tab in table:
... xx[tab['device']].append(tab['iface'])
...
>>> xx
defaultdict(<type 'list'>, {'a': ['i1', 'i2', 'i4', 'i3'], 'b': ['i5', 'i7']})
>>> yy = dict(xx)
>>> yy
{'a': ['i1', 'i2', 'i4', 'i3'], 'b': ['i5', 'i7']}
>>> new_table = []
>>> for a in yy:
... new_table.append({'device': a, 'iface': yy[a]})
...
>>> new_table
[{'device': 'a', 'iface': ['i1', 'i2', 'i4', 'i3']}, {'device': 'b', 'iface': ['i5', 'i7']}]
答案 1 :(得分:0)
我选择将列表table
中的项目按设备值收集到地图中,并在迭代同一设备的新项目时继续扩展iface
列表:
table=[{'device': 'a', 'iface': 'i1'}, {'device': 'a', 'iface': 'i2'}, {'device': 'a', 'iface': 'i4'}, {'device': 'b', 'iface': 'i5'}, {'device': 'a', 'iface': 'i3'}, {'device': 'b', 'iface': 'i7'}]
new_table = []
tmp_map = {}
for itm in table:
map_itm = tmp_map.get(itm['device'])
if not map_itm:
tmp_map[itm['device']] = {'device':itm['device'] ,'iface': [itm['iface']]}
else:
tmp_map[itm['device']]['iface'] = [itm['iface']]+ map_itm['iface']
print tmp_map.values()
<强>输出:强>
[{'device': 'a', 'iface': ['i3', 'i4', 'i2', 'i1']}, {'device': 'b', 'iface': ['i7', 'i5']}]
答案 2 :(得分:0)
你做了一本字典。然后,您不能在列表中的键和值之间建立链接。如果你想要类似于字典的东西,你可以做两个循环,一个用于键,另一个用于值,然后将其包含在列表中。您可以要求System.out.println(键+“:”+值)
之类的内容