如何将我列出的号码加在一起
How to add my listed numbers together
我遇到的问题是:"Total of the elements in the second list: 62"
如何添加 "second list" 中的每个元素?我在最后显示了这个:(45、12、5)。那不是我想要的。我想要号码:62。这是我在 stackoverview 上的第一个问题,非常感谢大家的帮助。
sequence = range(5,25,4)
first_list = list(sequence)
print("First List:", first_list)
print("Elements in the first list:")
for element in sequence:
print (element)
sequence_second = range(26,0,-7)
second_list = list(sequence_second)
print ("Second List: ", second_list)
for element in sequence_second:
print(element)
add = (second_list [0] + sequence_second [1], + sequence_second [2], + sequence_second[3])
print(add)
使用求和函数:
>>> sequence_second = range(26,0,-7)
>>> second_list = list(sequence_second)
>>> second_list
[26, 19, 12, 5]
>>> sum(second_list)
62
您可以使用内置函数sum()
。
就做sum(second_list)
.
如果你只想要前 4 个元素的总和,那么这样做:
sum(second_list[:4])
使用 for 循环
add = 0;
for element in sequence_second:
add = add + element
print(add)
输出 62
我遇到的问题是:"Total of the elements in the second list: 62" 如何添加 "second list" 中的每个元素?我在最后显示了这个:(45、12、5)。那不是我想要的。我想要号码:62。这是我在 stackoverview 上的第一个问题,非常感谢大家的帮助。
sequence = range(5,25,4)
first_list = list(sequence)
print("First List:", first_list)
print("Elements in the first list:")
for element in sequence:
print (element)
sequence_second = range(26,0,-7)
second_list = list(sequence_second)
print ("Second List: ", second_list)
for element in sequence_second:
print(element)
add = (second_list [0] + sequence_second [1], + sequence_second [2], + sequence_second[3])
print(add)
使用求和函数:
>>> sequence_second = range(26,0,-7)
>>> second_list = list(sequence_second)
>>> second_list
[26, 19, 12, 5]
>>> sum(second_list)
62
您可以使用内置函数sum()
。
就做sum(second_list)
.
如果你只想要前 4 个元素的总和,那么这样做:
sum(second_list[:4])
使用 for 循环
add = 0;
for element in sequence_second:
add = add + element
print(add)
输出 62