如何将元组列表中的两个元素分组为字典?
问题描述:
我想总结水果和颜色。有水果的元组及其相应颜色的名单,我希望计算的黄色的水果,然后构造一个词典:如何将元组列表中的两个元素分组为字典?
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}
问题是什么?
答
你依靠的是按水果排序的元组,但事实并非总是如此。为了处理水果在词典yellow_fruit
中存在或不存在的两种情况,我们使用yellow_fruit.get(fruit, 0)
,其或者返回yellow_fruit[fruit]
(如果fruit
存在于yellow_fruit
中)或0
(如果它不存在)。请注意,字典是无序的,所以如果您重新运行程序,打印的键/值对可以自行排列。
tuple_list = [
('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'),
]
yellow_fruit = {}
for fruit, colour in tuple_list:
if colour == 'yellow':
yellow_fruit[fruit] = yellow_fruit.get(fruit, 0) + 1
print(yellow_fruit) # {'banana': 1, 'orange': 2, 'grape': 2, 'peach': 4, 'pear': 1}
+0
非常感谢你!我的问题解决了,你让我知道dict.get()非常有帮助! – user5802211
你会只是做'collections.Counter(F为F,C水果如果c == '黄')' – vaultah
你开始用'N = 1' *它是否是黄*。另外,解释为什么你期望不同的输出会有所帮助,所以读者不必自行分析。 – jonrsharpe
@jonrsharpe即使我把if语句改成'if fruit [i] [0] == fruitname和fruit [i] [1] =='yellow':',它不起作用。 – user5802211