循环遍历对象以在python中创建新对象

时间:2018-05-23 17:06:46

标签: python python-3.x

我有一个看起来像这样的对象

object_1 = [(1,"car"),
            (1,"stuff"),
            (2,"things"),
            (2,"more stuff"),
            (3,"less thing"),
            (4,"diff_things")]

我需要一种pythonic方法来遍历它并使其成为这个

[(1,["car","stuff"]),
(2,["things","more stuff"]),
(3,"less thing"),
(4,"diff_things")]

看起来很简单,但我似乎无法让它正常工作。

1 个答案:

答案 0 :(得分:1)

扩展我上面的评论,如果你规范化输出类型,你可以这样解决:

from collections import defaultdict

dct = defaultdict(list)
for a, b in object_1:
  dct[a].append(b)
print(sorted(dct.items()))