我有一个看起来像这样的对象
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")]
看起来很简单,但我似乎无法让它正常工作。
答案 0 :(得分:1)
扩展我上面的评论,如果你规范化输出类型,你可以这样解决:
from collections import defaultdict
dct = defaultdict(list)
for a, b in object_1:
dct[a].append(b)
print(sorted(dct.items()))