果物と色を要約したいと思います。そこ果物とそれに対応する色でタプルのリストがあり、私は黄色の色の果物をカウントしたい、そして、辞書を構築する:タプルのリスト内の2つの項目を辞書としてグループ化するにはどうすればよいですか?
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}
何が問題ですか?
(F果物でF、Cのためであれば、C == '黄色')'あなたはで始まる – vaultah
'N = 1' *それが黄色だかどうか*。また、なぜ異なる出力が期待されるのか説明すると参考になりますので、読者はそれ自体を比較する必要はありません。 – jonrsharpe
@jonrsharpe私はif文を 'fruit [i] [0] == fruitnameとfruit [i] [1] ==' yellow ':'のように変更しても動作しません。 – user5802211