将列表与函数相乘

2024-06-09 09:29:25 发布

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

我有两个函数(price()sold()),它们创建一个随机的数字列表。第三个函数(itemSale())假设将price()sold()的列表相乘,根据答案创建一个新列表,然后显示它们。这是我的密码:

def main():
    itemSale()

def price():
    priceList = [1,2,3,4,5,6,7,8,9,10]
    for i in range (10):
        priceList[i] = random.uniform(1.0,1000.0)
        print("${:7.2f}".format(priceList[i]))
    return priceList[i]

def sold():
    itemsSold = [1,2,3,4,5,6,7,8,9,10]
    for i in range (10):
        itemsSold[i] = random.randint(0,200)
        print ('%i' %(itemsSold[i]))
    return itemsSold[i]

def itemSale():
    itemSale = [1,2,3,4,5,6,7,8,9,10]
    totSale = sold()*price()
    print("${:7.2f}".format(totSale))

它将显示前两个函数中随机生成的数字,但只会将这些列表中的最后一个数字相乘,我不知道如何让它正常工作。你知道吗

#from sold()
146
119
52
117
200
30
74
23
151
161
#from price()
$ 308.23
$ 116.05
$ 531.93
$ 730.77
$ 917.83
$ 949.44
$ 750.43
$ 427.39
$ 125.91
$  14.06
#from itemSale()
$2262.96

Tags: 函数infrom列表fordefrange数字
1条回答
网友
1楼 · 发布于 2024-06-09 09:29:25

每个函数只返回最后一项,为什么不返回整个列表?e、 g变化

return priceList[i]

return priceList

然后需要将列表中的每个成对项相乘

totSale = sold()*price()

变成

totSale = sum([x*y for x,y in zip(sold(),price())])

相关问题 更多 >