我想總結水果和顏色。有水果的元組及其相應顏色的名單,我希望計算的黃色的水果,然後構造一個詞典:如何將元組列表中的兩個元素分組爲字典?
yellowfruit= { 'banana': 1, 'grape' : 2, 'orange': 2, 'peach': '4', 'pear':1 }
以下是水果的信息
fruit= [
('apple', 'green'),
('apple', 'red'),
('banana', 'yellow'),
('grape', 'green'),
('grape', 'yellow'),
('grape', 'yellow'),
('grape', 'red'),
('orange', 'yellow'),
('orange', 'yellow'),
('mango', 'green'),
('peach', 'yellow'),
('peach', 'red'),
('peach', 'yellow'),
('peach', 'yellow'),
('peach', 'red'),
('peach', 'yellow'),
('peach', 'red'),
('pear', 'yellow'),
]
這些是我的意見代碼:
fruit= [
('apple', 'green'),
('apple', 'red'),
('banana', 'yellow'),
('grape', 'green'),
('grape', 'yellow'),
('grape', 'yellow'),
('grape', 'red'),
('orange', 'yellow'),
('orange', 'yellow'),
('mango', 'green'),
('peach', 'yellow'),
('peach', 'red'),
('peach', 'yellow'),
('peach', 'yellow'),
('peach', 'red'),
('peach', 'yellow'),
('peach', 'red'),
('pear', 'yellow'),
]
yellowfruit = { } # create an empty dictionary
fruitname = fruit[0][0] # 'apple' is the first fruit
for i in range(len(fruit)): # loop over the tuples in the fruit list
if fruit[i][0] == fruitname:
if fruit[i][1] == 'yellow':
# for the same kind of fruit, if its colour is yellow, count update for 1
n += 1
else: # if the same kind of fruit but not the colour of yellow
continue
else:
n = 1 # if not the same kind of fruit, refill the count as 1
fruitname = fruit[i][0] # if the fruit change, always update the current item as the fruit name
yellowfruit[fruitname] = n # create the dictionary
print(yellowfruit)
結果:
{'peach': 4, 'banana': 1, 'orange': 2, 'grape': 3, 'pear': 1, 'mango': 1}
問題是什麼?
你會只是做'collections.Counter(F爲F,C水果如果c == '黃')' – vaultah
你開始用'N = 1' *它是否是黃*。另外,解釋爲什麼你期望不同的輸出會有所幫助,所以讀者不必自行分析。 – jonrsharpe
@jonrsharpe即使我把if語句改成'if fruit [i] [0] == fruitname和fruit [i] [1] =='yellow':',它不起作用。 – user5802211