【问题标题】:From a parameter of tuple, trying to find two sums从元组的一个参数,试图找到两个和
【发布时间】:2020-05-03 23:59:16
【问题描述】:

一个从第一个数字开始每隔一个数字相加,第二个和从第二个数字开始。 例子;

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

我不确定如何从用户输入中获取元组,而且我对元组的工作不多,所以我不确定如何将它们彼此相加,尤其是必须从不同的开始点。

任何帮助将不胜感激!

【问题讨论】:

  • 从元组中获取值的方式与从列表中获取值的方式相同。所以在everyOtherSumDiff 代码中好像参数eg 是一个列表。
  • 我不确定如何从用户输入中获取元组,而且我对元组的工作并不多,所以我不确定如何将它们彼此相加,尤其是必须从不同的起点出发。 你能说得更具体些吗?你有没有尝试过什么,做过什么研究?
  • 我不确定如何从用户输入中获取元组这部分问题与stackoverflow.com/questions/7378091/… 重复,我没有工作很多元组,所以我不知道如何将它们相加在一起,尤其是必须从不同的起点开始,这还不清楚。

标签: python sum tuples


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 为什么不一次获取所有输入?
    • 说实话,我只是没想到。这种格式似乎是“最安全的”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-04
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多