我正在尝试解决以下问题:
定义函数sum()和求和的函数multiply() 并且(分别)乘以数字列表中的所有数字。 例如,sum([1,2,3,4])应该返回10,然后相乘 ([1,2,3,4])应该返回24。
到目前为止,我有以下内容:
def sums(listofnums):
total=0
for i in (listofnums):
total=total+i
return total
def multiply(listofnums):
total =1
for i in (listofnums):
total = total*i
return total
listofnums=[]
nums=input("Enter a list of numbers seperated by commas: ").split(",")
nums2=[float(i) for i in nums]
listofnums.append(nums2)
print(listofnums)
print (sums(listofnums))
print (multiply(listofnums))
返回以下内容:
*Enter a list of numbers seperated by commas: 1,2,3
[[1.0, 2.0, 3.0]]
Traceback (most recent call last):
File "C:\Python34\46 simple python ex\sum() and mult() v2.py", line 19, in <module>
print (sums(listofnums))
File "C:\Python34\46 simple python ex\sum() and mult() v2.py", line 4, in sums
total=total+i
TypeError: unsupported operand type(s) for +: 'int' and 'list'*
我怀疑问题是我的函数求和并且只能使用形式列表(x,x,x,x)或[x,x,x,x]以及我返回的值是[[ X,X,X]]。
我该如何解决这个问题?
(注意我认为当我在代码中直接手动输入一组形式为[x,x,x]的数字时,其余的代码是精细的b / c。)