我需要两个数组(在我下面的代码中):“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
这似乎是一个使用zip函数的好例子。它获取两个列表作为参数(在您的例子中是
donlist
和charlist
),并创建这些列表的迭代器,这样您就可以迭代一次,将donlist
中的值添加到正确的位置。zip
示例:将输出
我强烈建议在创建第三个之前生成数据列表,这样您就可以
这是从迭代器创建列表的简单语法。你可以阅读更多关于它的here。你知道吗
通过这种方式,您可以保证它适用于在计算过程中没有生成这些列表的情况,例如,用户输入值的情况。你知道吗
列表生成/输入后,您可以:
最终每个慈善机构都有它的捐赠价值。你知道吗
现在,您可以按慈善机构编号对
d
进行索引,并获得捐赠的价值。你知道吗使用
dict
,以慈善机构编号为键。您只需将捐赠添加到相应的dict
值。如果dict
元素还不存在,则将其设置为零作为其初始值。 我使用的是defaultdict
:lambda: 0
参数将保证一个零值,如果键还不存在,否则您可以直接添加到它。你知道吗正在更新脚本(其他一些小改动):
注意:我删除了
array
导入,因为您在代码中只使用了list
。你知道吗相关问题 更多 >
编程相关推荐