【问题标题】:Multiplying Lists through Functions通过函数将列表相乘
【发布时间】:2016-03-10 20:36:52
【问题描述】:

我有两个函数(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

【问题讨论】:

标签: python list function python-3.x


【解决方案1】:

每个函数只返回最后一项,为什么不返回整个列表呢?例如改变

return priceList[i]

return priceList

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

totSale = sold()*price()

变成

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

【讨论】:

  • sum(imap(mul, sold(), price()))
  • totSale = sum([x*y for x,y in zip(sold(),price())]) 总结了一切,不是吗?我试图让每个索引中的每个值乘以其他列表索引值。所以x=[1,2,3,4]*y=[2,3,4,5]给我xy=[2,6,12,20]
  • 只需去掉 sum(...)
  • 大声哇,我觉得自己很愚蠢。我试过了,它给了我一个TypeError,但我没有意识到它在我的print 语句中,只是假设它在totSale 等式中。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2020-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-15
  • 1970-01-01
相关资源
最近更新 更多