[英]How do I add values that are in a python list without having to do it manually
How do ia values in a list.列表中的 ia 值如何。
Like lets say i have 5 numbers 1, 2, 6, 23, 5 and i want to store their total inside a variable without having to do it manually.比如说我有 5 个数字 1、2、6、23、5,我想将它们的总数存储在一个变量中,而不必手动执行。
Because i will make the program let the user input their own values and i cant guess the values.因为我会让程序让用户输入他们自己的值,而我无法猜测这些值。
this is what i got when i searched it up这是我搜索时得到的
l = list(range(3))
l.append([3, 4, 5])
print(l)
# [0, 1, 2, 100, 'new', [3, 4, 5]]
If you are trying to allow users to input things to the list, you can try如果您试图让用户在列表中输入内容,您可以尝试
for i in range(num):
list.append(int(input('Enter a number: ')))
where num
is how many inputs you want其中num
是您想要的输入数量
and then you can use Python sum()
function to find the sum:然后你可以使用 Python sum()
function 求和:
total = sum(list)
Simple way:简单的方法:
total = sum(myList)
What you need to do is to loop through all the numbers and calculate the total.您需要做的是遍历所有数字并计算总数。
myList = [1, 2, 6, 23, 5]
total = 0
for number in myList:
total = total + number
print(total)
Output Output
37
Alternative Method替代方法
myList = [1, 2, 6, 23, 5]
total = sum(myList)
print(total)
Output Output
37
I hope this answer's your question!我希望这回答了你的问题! If you need any clarifications just feel free to comment below ^-^ I'm here to help!如果您需要任何澄清,请随时在下面发表评论^-^我在这里为您提供帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.