将匹配的元组元素与其他元组的唯一元素组合在一起

时间:2017-10-22 15:48:22

标签: python python-3.x tuples list-comprehension

我想从元组中创建一个新元组列表,这些元组与第一个元素上的其他元组匹配。当元组与第一个元素上的另一个元组匹配时,我还想将第三个元素添加到匹配的元组中。

数据示例(元组有3个字符串):

unique_3 = [(apple, banana, fruit),
           (apple, banana, dessert),
           (eggplant, fig, plant),
           (eggplant, fig, purple),
           (iris, jaguar, horse)]

我正在寻找的输出:

new_list =[(apple, banana, [fruit, dessert]), 
           (eggplant, fig, [plant, purple]),
           (iris, jaguar, horse)]

我只需要匹配元组的第一个元素。所以我试过这个:

new_list= [next(i for i, v in enumerate(unique_3) if v[0] == any(v[0]))]  

返回没有结果的StopIteration,所以我在构建new_list方面做得还不够。

1 个答案:

答案 0 :(得分:1)

您可以使用groupby根据每个元组的第一个元素对项目进行分组,

from itertools import groupby

unique_sorted = sorted(unique_3, key = lambda x: x[0])

group_list = []
for key, group in groupby(unique_sorted, lambda x: x[0]):
        group_list.append(list(group))

new_list = [(x[0][0], x[0][1], [y[-1] for y in x]) for x in group_list]

在每次for次迭代中,groupby返回具有相同第一元组元素group的元素组key。元素必须是连续的才能成为组,因此原始列表在第一步中基于每个元组中的第一个值进行排序。