我有一個元組串列
a = [('name', 'color'),('fruit', 'color'),('thing', 'type'),('sport', 'type')]
我想加入按第二個元素分組的第一個元素。輸出應該看起來像。
a = [('name fruit', 'color'),('thing sport', 'type')]
uj5u.com熱心網友回復:
您可以dict使用要分組的鍵創建并將值添加到listbase key。對于這種方法,您可以使用collections.defaultdict或者如果您不想匯入任何可以使用dict.setdefault的 .
from collections import defaultdict
a = [('name', 'color'),('fruit', 'color'),('thing', 'type'),('sport', 'type')]
res = defaultdict(list)
res_2 = {}
for tpl in a:
res[tpl[1]].append(tpl[0])
res_2.setdefault(tpl[1], []).append(tpl[0])
# Now you can use `res_2` instead of `res`
lst = [(' '.join(v), k) for k,v in res.items()]
print(lst)
另一種選擇是使用itertools.groupby. 對于這種方法,您可以設定tuple要分組的值。(因為你想對每個元組的第二個基值進行分組,你可以設定groupbylike的鍵lambda x: x[1]。)
from itertools import groupby
res = []
for key, group in itertools.groupby(a, lambda x: x[1]):
res.append((' '.join(tpl[0] for tpl in group), key))
print(res)
輸出:
[('name fruit', 'color'), ('thing sport', 'type')]
uj5u.com熱心網友回復:
您可以在串列推導itertools.groupby()中使用and來實作此目的:operator.itemgetter()
from itertools import groupby
from operator import itemgetter
my_list = [('name', 'color'),('fruit', 'color'),('thing', 'type'),('sport', 'type')]
new_list = [(' '.join(item[0] for item in g_list), x) for x, g_list in groupby(my_list, itemgetter(1))]
# where `new_list` will be holding the value:
# [('name fruit', 'color'), ('thing sport', 'type')]
uj5u.com熱心網友回復:
不需要匯入可能不是超級快:
new = [(a[k][0] " " a[k 1][0], a[k][1]) for k in range(0, len(a), 2)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/521151.html
標籤:Python细绳加入元组
