![](/img/trans.png)
[英]Python: Join each element different lists of lists in one list of lists
[英]Python: Join lists of lists by the first element
我正在嘗試通過列表中的第一個元素組合列表/元組列表-像這樣:
輸入:
[(1, [32, 432, 54]), (1, [43, 54, 65]), (2, [2, 43, 54]), (2, [1, 5, 6])]
輸出:
[(1, [32, 432, 54], [43, 54, 65]), (2, [2, 43, 54], [1, 5, 6])]
列表實際上是按第一個元素排序的,就像在我的示例輸入中一樣,並且最后元組是否是列表也沒有關系。
有沒有一種有效的/ python方式來做到這一點?
使用itertools.groupby
和list comprehension :
>>> lst = [(1, [32, 432, 54]), (1, [43, 54, 65]), (2, [2, 43, 54]), (2, [1, 5, 6])]
>>> import itertools
>>> [(key,) + tuple(v for k, v in grp)
... for key, grp in itertools.groupby(lst, key=lambda x: x[0])]
[(1, [32, 432, 54], [43, 54, 65]), (2, [2, 43, 54], [1, 5, 6])]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.