我有一份清单
List = [['ServerA','Envname1','abc','xyz'],
['ServerA','Envname2','abc','xyz'],
['ServerB','Envname3','aaa','bbb'],
['ServerC','EnvName4','uuu','vvv'],
['ServerB','Envname5','aaa','bbb']]
如果服务器相同,则内部列表的第2和第3索引处的值将相同。
例如: - 在第一个列表['ServerA','Envname1','abc','xyz']
和第二个列表['ServerA','Envname2','abc','xyz']
服务器相同(' ServerA'),因此值' abc'和' xyz'是一样的。
同样,第3和第4中ServerB的值相同' aaa'和' bbb'
即使服务器相同,也只有Envname正在改变。
我想要的最终列表是将所有具有相同名称的服务器分组并相应地添加所有Envnames,如果服务器名称相同,则其余元素将相同。
预期清单
Final_list = [['ServerA','Envname1,Envname2','abc','xyz'],
['ServerB','Envname3,Envname5','aaa','bbb'],
['ServerC','EnvName4','uuu','vvv']]
有人可以就此提出建议吗?
答案 0 :(得分:2)
这应该有效:
l = [['ServerA','Envname1','abc','xyz'],
['ServerA','Envname2','abc','xyz'],
['ServerB','Envname3','aaa','bbb'],
['ServerC','EnvName4','uuu','vvv'],
['ServerB','Envname5','aaa','bbb'],
]
d = {}
for item in l:
key = (item[0], item[2], item[3])
env = d.setdefault(key, [])
env.append(item[1])
final_list = [[k[0], ",".join(v), k[1], k[2]] for k, v in d.items()]
print final_list
输出:
[['ServerA', 'Envname1,Envname2', 'abc', 'xyz'],
['ServerB', 'Envname3,Envname5', 'aaa', 'bbb'],
['ServerC', 'EnvName4', 'uuu', 'vvv'],
]
答案 1 :(得分:0)
from itertools import groupby,chain
from operator import itemgetter
List_server = [['ServerA','Envname1','abc','xyz'],
['ServerA','Envname2','abc','xyz'],
['ServerB','Envname3','aaa','bbb'],
['ServerC','EnvName4','uuu','vvv'],
['ServerB','Envname5','aaa','bbb']]
List_server=sorted(List,key=lambda x:x[0][-1])
print [set(chain(*list(g))) for i,g in groupby(List_server,key=itemgetter(0))]
output: [set(['xyz', 'abc', 'ServerA', 'Envname2', 'Envname1']),
set(['Envname5', 'aaa', 'bbb', 'ServerB', 'Envname3']),
set(['EnvName4', 'uuu', 'vvv', 'ServerC'])]
explantion:
List_server=sorted(List,key=lambda x:x[0][-1])
key=itemgetter(0)
注意:不要将Python关键字用作变量