嘿 :) 我怎樣才能比較串列,以便串列的所有元素都匹配除了一個元素的顏色?如果所有其他元素都匹配,則應將串列連接為一個。
fruitlist = [['Apple', 'red', 10], ['Apple', 'green', 10], ['Apple', 'pink', 10], ['Apple', 'yellow', 20], ['Banana', 'yellow', 10]]
輸出:
fruitlist = [['Apple', 'red, green, pink', 10], ['Apple', 'yellow', 20],['Banana', 'yellow', 10]]
這里是否還有適用于更長串列的解決方案?(不包括一種或多種元素)
uj5u.com熱心網友回復:
使用中間字典,然后按如下方式構建輸出串列:
from collections import defaultdict
mdict = defaultdict(list)
fruitlist = [['Apple', 'red', 10], ['Apple', 'green', 10], ['Apple', 'pink', 10], ['Apple', 'yellow', 20], ['Banana', 'yellow', 10]]
for fruit, colour, n in fruitlist:
mdict[fruit, n].append(colour)
print([[fruit, ', '.join(v), n] for (fruit, n), v in mdict.items()])
輸出:
[['Apple', 'red, green, pink', 10], ['Apple', 'yellow', 20], ['Banana', 'yellow', 10]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/432191.html
標籤:Python python-3.x 列表
下一篇:`print()`是如何作業的?
