元组列表中的元组列表

时间:2017-06-26 09:05:30

标签: python list tuples

假设我有一个目前按第一个元素排序的元组列表:

tuple_list = [(1, "hello", "apple"), (1, "no", "orange"),
    (2, "bye", "grape"), (3, "okay", "banana"),
    (4, "how are you?", "raisin"), (4, "I'm doing well", "watermelon")]

我想根据每个元组的第一个元素将这个元组列表转换为元组列表的列表。

例如:

new_tuple_list = [[(1, "hello", "apple"), (1, "no", "orange")],
    [(2, "bye", "grape")], [(3, "okay", "banana")],
    [(4, "how are you?", "raisin"), (4, "I'm doing well", "watermelon")]]

2 个答案:

答案 0 :(得分:2)

使用itertools.groupby根据整数对项目进行分组:

from itertools import groupby

lst = [list(g)for _, g in groupby(tuple_list, lambda x: x[0])]
print(lst)
[[(1, 'hello', 'apple'), (1, 'no', 'orange')], 
 [(2, 'bye', 'grape')], 
 [(3, 'okay', 'banana')], 
 [(4, 'how are you?raisin'), (4, "I'm doing well", 'watermelon')]]

答案 1 :(得分:2)

您可以使用itertools.groupby

[list(x) for k, x in itertools.groupby(tuple_list, operator.itemgetter(0))]