我在Python中有一个这样的列表:
[('a', 'b'), ('a', 'c'),('d','f')]
并且我想要加入具有相同第一项和结果的项目:
[('a', 'b', 'c'),('d','f')]
答案 0 :(得分:1)
这是一种方法。为了提高效率,我们以第一个值作为键构建dict
。我们将值按它们出现的顺序保留(如果使用Python> = 3.7,元组也将保留其原始顺序-否则,您将不得不使用collections.OrderedDict
)
def join_by_first(sequences):
out = {}
for seq in sequences:
try:
out[seq[0]].extend(seq[1:])
except KeyError:
out[seq[0]] = list(seq)
return [tuple(values) for values in out.values()]
join_by_first([('a', 'b'), ('a', 'c'),('d','f')])
# [('a', 'b', 'c'), ('d', 'f')]
答案 1 :(得分:0)
您无法编辑tuples
-不可更改。您可以使用lists
,然后将其全部转换回tuples
:
data = [('a', 'b'), ('a', 'c'),('d','f')]
new_data = []
for d in data # loop over your data
if new_data and new_data[-1][0] == d[0]: # if something in new_data and 1st
new_data[-1].extend(d[1:]) # ones are identical: extend
else:
new_data.append( [a for a in d] ) # not same/nothing in: add items
print(new_data) # all are lists
new_data = [tuple(x) for x in new_data]
print(new_data) # all are tuples again
输出:
[['a', 'b', 'c'], ['d', 'f']] # all are lists
[('a', 'b', 'c'), ('d', 'f')] # all are tuples again
答案 2 :(得分:0)
我觉得最简单的解决方案是建立一个词典,其中:
一旦有了我们就可以构建输出列表:
from collections import defaultdict
def merge(pairs):
mapping = defaultdict(list)
for k, v in pairs:
mapping[k].append(v)
return [(k, *v) for k, v in mapping.items()]
pairs = [('a', 'b'), ('a', 'c'),('d','f')]
print(merge(pairs))
这将输出:
[('a', 'b', 'c'), ('d', 'f')]
此解决方案位于 O(n)中,因为我们仅对pairs
中的每个项目进行两次迭代。