列表列表中的三元组列表

时间:2016-04-14 22:02:14

标签: python list dictionary tuples

我需要每个元组中的第一个项目作为返回相应项目列表列表的键。例如......

这是我的输入数据:

my_problem = [(1,20,400), (1,30,450), (2,40,525), (2,50,600), (2,70,680),(3,80,700), (3,90,980)]

这就是我想要实现的目标:

my_solution = {'1': [[20,400],[30,450]], '2': [[40,525],[50,600],[70,680]], '3': [[80,700], [90,980]]}

我的实际列表包含数千个不同长度的元组。

3 个答案:

答案 0 :(得分:3)

使用defaultdict。这些漂亮的结构本质上是字典,可以在插入密钥时使用默认值进行初始化:

from collections import defaultdict

solution = defaultdict(list) # create defaultdict with default value []
for item in my_problem:
    solution[item[0]].append(list(item[1:]))

并转换回字典(虽然这是不必要的,因为defaultdict已经具有常规字典的行为)你可以做

my_solution = dict(solution)

Python 3中的一个稍微整洁的配方

(感谢tobias_k指出这一点)

在Python 3中,您可以替换丑陋的item[0]等调用以使用以下内容:

solution = defaultdict(list)
for first, *rest in my_problem:
    solution[first].append(rest)

答案 1 :(得分:0)

data = {}
for item in my_problem:
    data[item[0]] = data.get(item[0], []) + [item[1:]]

制作一个新词典来保存结果;浏览输入列表,并将其添加到字典中 - 如果已经存在给定键的列表,则添加到该列表中,否则启动一个空列表并添加到该列表中。

答案 2 :(得分:-1)

#! python3
my_problem = [(1,20,400), (1,30,450), (2,40,525), (2,50,600), (2,70,680),(3,80,700), (3,90,980)]

import collections
my_solution = collections.defaultdict(list)
for k,*v in my_problem:
    my_solution[k].append(v)

print(my_solution)