一个从第一个数字开始的其他数字相加,第二个和从第二个数字开始。举例来说。
Tuple= (1, 2, 3, 4, 5, 6, 7, 8)
Sum1= 1+3+5+7
Sum2= 2+4+6+8
这是我目前所做的。
def everyOtherSumDiff(eg):
a=0
b=0
for i in (eg, 2):
a+=i
return a
eg=(1, 2, 3, 4, 5, 6, 7, 8)
print(everyOtherSumDiff(eg))
我不知道如何从用户输入中获取元组 我也没有用过很多元组 所以我不知道如何将它们相加,从其他数开始,特别是要从不同的起点开始。
如果有任何帮助,我将感激不尽
你可以使用分片语法[start:stop:step]来处理这个问题。
>>> tup = (1, 2, 3, 4, 5, 6, 7, 8)
>>> sum(tup[0::2]) # sum every second element, starting index 0
16
>>> sum(tup[1::2]) # sum every second element, starting index 1
20
我准备在covfefe19的回答基础上,增加元组部分。
my_tuple = () #I define the tuple
user_input = input('Please write a series of number one at a time. Press q to quit') #I #define the input statement
my_tuple = (int(user_input),) #I add the number from the input into the tuple as a number
while user_input.isdigit(): #Here I use the "isdigit()" to create the condition for the #while loop. As long as the input is a digit the input will keep poppin up
user_input = input()
if user_input.isdigit():
my_tuple = my_tuple + (int(user_input),) #I add the input as a number to the tuple
else:
pass #if input not a number, then pass and go on the next part of the function
else:
print('You have quit the input process')
every_second = sum(my_tuple[0::2]) ## This is covfefe19's solution to tuple
every_other = sum(my_tuple[1::2]) ## so as this
print(my_tuple)
print(every_second, '\n', every_other) ##This prints the answer
希望这对输入的制作和存储有一点帮助!
如你所见,你必须调用创建的元组,并将输入添加为元组。(user_input,)
. 这将把每一个插入到输入中的值加到最后一个索引的 my_tuple