这个英文标题的中文翻译为: 用Python将具有共同键的2个列表添加到字典中

2024-05-12 21:00:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python还不熟悉。我正在从csvfile中提取两行。你知道吗

Foodlist = ['apple, carrot, banana','chocolate, apple', 'strawberry, orange, carrot']

数量表对应于其序列中的每个项目。你知道吗

Quantity = ['1,2,1','2,5','1,2']

如何将这两个具有公用键的列表合并到字典中?我尝试过拆分和合并,但是由于公用键的缘故,数量被覆盖了。你知道吗

我试图输出:

{'Apple: totalquantity','Banana: totalquantity', 
 'Carrot: totalquantity','Chocolate: totalquantity',
 'orange: totalquantity', 'strawberry: totalquantity'}

请帮帮我!你知道吗

有没有什么地方可以提取食物的csvfile行并在字典中赋值?你知道吗

cvs文件如下:

第1行: 苹果、胡萝卜、香蕉 巧克力、苹果 草莓、橘子、胡萝卜

第2行: 1,2,1 2,5 1,2个


Tags: csvfile项目苹果apple数量字典序列公用
2条回答

使用集合.default\u dict建立一个字典来计算你的项目。你知道吗

In [1]: from collections import defaultdict

In [2]: items = defaultdict(int)

In [3]: Foodlist = ['apple, carrot, banana','chocolate, apple', 'strawberry, or
   ...: ange, carrot']

In [4]: Quantity = ['1,2,1','2,5','1,2']

In [5]: for which, counts in zip(Foodlist, Quantity):
   ...:     foods = [w.strip() for w in which.split(',')]  # Split the foods and remove trailing spaces
   ...:     nums = [int(c) for c in counts.split(',')]  # Split the counts are convert to ints
   ...:     for f, n in zip(foods, nums):
   ...:         items[f] += n
   ...:

In [6]: items
Out[6]:
defaultdict(int,
            {'apple': 6,
             'banana': 1,
             'carrot': 2,
             'chocolate': 2,
             'orange': 2,
             'strawberry': 1})

In [7]:

可以使用^{}聚合结果:

from collections import Counter

Foodlist = ['apple, carrot, banana','chocolate, apple', 'strawberry, orange, carrot']
Quantity = ['1,2,1','2,5','1,2']
res = Counter()

for f_list, q_list in zip(Foodlist, Quantity):
    for f, q in zip(f_list.split(', '), q_list.split(',')):
        res[f] += int(q)

print(res)

输出:

Counter({'apple': 6, 'chocolate': 2, 'carrot': 2, 'orange': 2, 'strawberry': 1, 'banana': 1})

相关问题 更多 >