我有一個 3d 串列,包含字串和數字。我需要計算每種顏色的總和。另外,每個專案占總顏色的百分比。
這就是我目前擁有的。
from collections import defaultdict
d = defaultdict(int)
dc = defaultdict(int)
l = [('red', 'apple', 7), ('red', 'car', 4), ('red', 'shoe', 3), ('blue', 'candy', 4), ('blue', 'bike', 5), ('green', 'melon', 2)]
for color, name, number in l:
d[color] = number
total = str(d)
for color, name, number in l:
dc[color] /= number
percent = str(dc)
print(total, percent)
它列印的是:
defaultdict(<class 'int'>, {'red': 14, 'blue': 9, 'green': 2}) defaultdict(<class 'int'>, {'red': 0.0, 'blue': 0.0, 'green': 0.0})
預期的輸出是:
red: 14
blue: 9
green: 2
red apple: 7/14 = 50%
red car: 4/14 = 29%
red shoe: 3/14 = 21%
blue candy: 4/9 = 44%
blue bike: 5/9 = 56%`
uj5u.com熱心網友回復:
您需要再迭代一次dc并使用dbase的值color_key。
from collections import defaultdict
d = defaultdict(int)
dc = defaultdict(int)
l = [('red', 'apple', 0), ('red', 'car', 0), ('red', 'shoe', 0), ('blue', 'candy', 4), ('blue', 'bike', 5), ('green', 'melon', 2)]
for color, name, val in l:
d[color] = val
dc[(color, name)] = val
print(d)
dc = {f"{color} {name}" : round(val / d[color], 2) if d[color]!=0 else 'division by zero'
for (color, name), val in dc.items()}
print(dc)
輸出:
# print(d)
defaultdict(<class 'int'>, {'red': 14, 'blue': 9, 'green': 2})
# print(dc)
{'red apple': 0.5, 'red car': 0.29, 'red shoe': 0.21, 'blue candy': 0.44, 'blue bike': 0.56, 'green melon': 1.0}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/535002.html
上一篇:字串中的重復字符
