[英]Sum not performing addition on the list specified in python
So i've got the list, i've changed it from strings to integers and now i need to add them all up for a total.所以我得到了列表,我已经将它从字符串更改为整数,现在我需要将它们全部加起来。 The only thing is, my code is not doing the calculation, even when the function is called.唯一的问题是,即使调用了 function,我的代码也没有进行计算。 Here's my code;这是我的代码;
# create an empty list for your products.
products = []
# Asking for the number of elements to be inputted.
n = int(input("Enter number of products you're buying : "))
# Some UI for the customer.
print("What are these products?")
# iterating until the range that has been chosen.
for i in range(0, n):
ele = input()
products.append(" - " + ele) # adding the element
def totalPrice():
price = [int(cost[i])]
print(sum(price))
# Some UI for the customer.
print("How much do those items cost?")
# create an empty list for your prices.
cost = []
# iterating until the range of the products array.
for i in range(products.__len__()):
ele = str(input())
cost.append(ele) # adding the element
# concatenating the lists, putting them in descending order and displaying them.
newList = [i + j for i, j in zip(cost, products)]
newList.sort(reverse=True)
print("Your products are : " + str(newList))
totalPrice()
The function should change the 'cost' list of strings to integers in a new list and add them all together, if i try to target the index of the 'price' list, it gives mean an iteration error. function 应该将字符串的“成本”列表更改为新列表中的整数并将它们加在一起,如果我尝试定位“价格”列表的索引,则意味着迭代错误。 Do i need to specify addition?我需要指定添加吗? Am i using the wrong function?我是否使用了错误的 function?
In the function,在 function 中,
price = [int(cost[i])]
This puts a single element into the list price
, using the global value of i
that was left over after that for i in range(products.__len__()):
loop ran at the top level.这会将单个元素放入列表price
,使用i
的全局值,该值在for i in range(products.__len__()):
循环运行在顶层之后剩余。 (Incidentally, don't call .__len__()
yourself - the built-in len
is designed to do it for you - and don't loop that way anyway .) (顺便说一句,不要自己调用.__len__()
- 内置len
旨在为您执行此操作 - 并且无论如何不要那样循环。)
if i try to target the index of the 'price' list, it gives mean an iteration error.如果我尝试以“价格”列表的索引为目标,则意味着迭代错误。
I have no idea what this is supposed to mean.我不知道这应该是什么意思。
If you want to build a list of values corresponding to the original list, then you need to actually do that - either by iterating with a for
loop, or using a comprehension:如果要构建与原始列表相对应的值列表,则需要实际执行此操作-通过使用for
循环进行迭代或使用推导:
price = [int(c) for c in cost]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.