从元组的一个参数中,试图找到两个和

2024-10-04 07:28:32 发布

您现在位置:Python中文网/ 问答频道 /正文

一个从第一个数开始每隔一个数相加,第二个和从第二个数开始。 榜样

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))

我不知道如何从用户输入中获取元组,而且我也没有对元组做过很多工作,所以我不知道如何将它们彼此相加,尤其是从不同的起点开始

任何帮助都将不胜感激


Tags: 用户inforreturndef情况元组print
2条回答

我将以CovFe19的答案为基础,添加元组部分:

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的最后一个索引中

对此,可以使用切片语法[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

相关问题 更多 >