通过组合两个列表中的值来创建第三个列表

2024-09-27 09:24:21 发布

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

我需要两个数组(在我下面的代码中):“donlist”是一个1到100美元之间的随机捐赠金额列表,“charlist”是一个1到15之间的随机慈善数字列表。我需要用每个慈善机构的捐款总额创建第三个数组。因此,如果charity#3在“charlist”中出现8次,我必须从“donlist”中得到相应的float的总和。我完全不知道该怎么做,在过去的2-3个小时里我一直在想办法。有人知道怎么做吗?非常感谢。你知道吗

import random
from array import *

counter = 0
donlist = []
charlist = []

while counter != 100:
    d = random.uniform(1.00,100.00)
    c = random.randint(1,15)
    counter +=1
    donlist.append(d)
    donlist = [round(elem,2) for elem in donlist]
    charlist.append(c)
    if counter == 100:
        break

样本输出:

Charity    Total Donations
1          802.65
2          1212.25
3          108.25
4          9324.12
5          534.98
6          6235.12
7          223.18
8          11.12
9          3345.68
10         856.68
11         7123.05
12         6125.86
13         1200.25
14         468.32
15         685.26

Tags: 代码import列表counter数字random数组金额
3条回答

这似乎是一个使用zip函数的好例子。它获取两个列表作为参数(在您的例子中是donlistcharlist),并创建这些列表的迭代器,这样您就可以迭代一次,将donlist中的值添加到正确的位置。zip示例:

for a, b in zip(range(1, 5), range(5, 10)):
    print(a, b)

将输出

1 5
2 6
3 7
4 8

我强烈建议在创建第三个之前生成数据列表,这样您就可以

donlist = [ random.uniform(1.0, 100.0) for _ in range(0, 100) ]
charlist = [ random.randint(1, 15) for _ in range(0, 100) ]

这是从迭代器创建列表的简单语法。你可以阅读更多关于它的here。你知道吗

通过这种方式,您可以保证它适用于在计算过程中没有生成这些列表的情况,例如,用户输入值的情况。你知道吗

列表生成/输入后,您可以:

# this is the same as a list comprehension but for a dict
# https://docs.python.org/3/tutorial/datastructures.html#dictionaries
result = { char : 0 for char in range(1, 16) }
for don, char in zip(donlist, charlist):
    result[char] += don

最终每个慈善机构都有它的捐赠价值。你知道吗

>>> l1 = [1,1,3,4] # charity list
>>> l2 = [5,6,7,8] # donation list
>>> zip(l1,l2)
[(1, 5), (1, 6), (3, 7), (4, 8)]

>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for k,v in zip(l1,l2):
...    d[k] += v
...
>>> d
defaultdict(<type 'int'>, {1: 11, 3: 7, 4: 8})

现在,您可以按慈善机构编号对d进行索引,并获得捐赠的价值。你知道吗

使用dict,以慈善机构编号为键。您只需将捐赠添加到相应的dict值。如果dict元素还不存在,则将其设置为零作为其初始值。 我使用的是defaultdictlambda: 0参数将保证一个零值,如果键还不存在,否则您可以直接添加到它。你知道吗

正在更新脚本(其他一些小改动):

import random
from collections import defaultdict

donlist = []
charlist = []
totals = defaultdict(float)

counter = 0
while counter != 100:
    counter += 1
    d = random.uniform(1.00,100.00)  
    c = random.randint(1,15)  
    donlist.append(d)      
    donlist = [round(elem,2) for elem in donlist]
    charlist.append(c)      
    totals[c] += d

注意:我删除了array导入,因为您在代码中只使用了list。你知道吗

相关问题 更多 >

    热门问题