我遇到Python问题,希望有人可以帮助我。我有一个列表,例如这个:
list = [['a','b','c'],['a','c1','d1'],['b','c1','c2']]
我希望以一种所有具有相同索引[0]的数组将在一起的方式组合列表,因此它将如下:
a, b, c, c1, d1
b, c1, c2
我试过这样的事情,但我没有让它发挥作用..
list = [['a','b','c'],['a','c1','d1'],['b','c1','c2']]
empty_list = []
for i in list:
if i not in empty_list:
empty_list.append(i)
print empty_list
有人可以帮助我吗?
答案 0 :(得分:1)
你可以试试这个:)
old_list = [['a','b','c'],['a','c1','d1'],['b','c1','c2']]
prev = None
empty_list = []
for l in old_list: # iterate through each sub list, sub list as l
if l[0] == prev:
# append your elements to existing sub list
for i in l: # iterate through each element in sub list
if i not in empty_list[-1]:
empty_list[-1].append(i)
else:
empty_list.append(l) # create new sub list
prev = l[0] # update prev
print(empty_list)
# [['a', 'b', 'c', 'c1', 'd1'], ['b', 'c1', 'c2']]
答案 1 :(得分:1)
from itertools import groupby
from operator import itemgetter
listt = [['a','b','c'],['a','c1','d1'],['b','c1','c2']]
grouped = [list(g) for _,g in groupby(listt,itemgetter(0))]
result = [[item for sslist in slist for item in sslist] for slist in grouped]
答案 2 :(得分:0)
OrderedDict
可以完成大部分工作:
from collections import OrderedDict
l = [['a','b','c'], ['a','c1','d1'], ['b','c1','c2']]
d = OrderedDict()
for el in l:
d.setdefault(el[0], el[0:1]).extend(el[1:])
print(d.values())
答案 3 :(得分:0)
您也可以尝试使用defaultdict(list)
l = [['a','b','c'], ['a','c1','d1'], ['b','c1','c2']]
from collections import defaultdict
d_dict = defaultdict(list)
for i in l:
d_dict[i[0]].extend(i[1:])
[ list(k) + v for k, v in d_dict.items() ]
输出:
[['a', 'b', 'c', 'c1', 'd1'], ['b', 'c1', 'c2']]