Python3,Sum用户给定的元组

时间:2013-12-19 22:54:46

标签: python user-input

代码:

def sum_given(values):
    s = 0
    for i in zip(*values):
        s += int(i)
    return s

try:
    v_list = input("Enter values to be summed.\n> ")
except ValueError:
    print('Invalid input. Counting as a zero.')

result_of_sum = sum_given(v_list)
print(result_of_sum)

输出:

$ ./helloworld.py 
Enter values to be summed.
> 1,2,3,4,5
Traceback (most recent call last):
  File "./helloworld.py", line 13, in <module>
    result_of_sum = sum_given(v_list)
  File "./helloworld.py", line 6, in sum_given
    s += i
TypeError: unsupported operand type(s) for +=: 'int' and 'tuple'

我理解这个错误,但我不确定如何解决它。

我要做的是允许用户输入多个值或范围,并让python输出总和。

我还没有实现这个范围。

3 个答案:

答案 0 :(得分:1)

您不想在此处使用zip和splat语法。相反,您应该使用str.split来分隔逗号上的输入:

for i in values.split(","):

以下是演示:

>>> def sum_given(values):
...     s = 0
...     for i in values.split(","):
...         s += int(i)
...     return s
...
>>> v_list = input("Enter values to be summed.\n> ")
Enter values to be summed.
> 1,2,3,4,5
>>> result_of_sum = sum_given(v_list)
>>> print(result_of_sum)
15
>>>

但请注意,您可以使用sumgenerator expression来简化您的功能:

>>> def sum_given(values):
...     return sum(int(x) for x in values.split(","))
...
>>> v_list = input("Enter values to be summed.\n> ")
Enter values to be summed.
> 1,2,3,4,5
>>> result_of_sum = sum_given(v_list)
>>> print(result_of_sum)
15
>>>

答案 1 :(得分:1)

更加pythonic的方法是在理解,生成器或映射上用sum()替换for循环。

def sum_given(strValues):
    return sum(int(v) for v in strValues.split(","))

# output 15
print sum_given("1,2,3,4,5")

答案 2 :(得分:0)

>>> def sum_given():
...     answer = 0
...     for i in input("Enter numbers: ").split(','):
...         answer += int(i)
...     return answer
... 
>>> sum_given()
Enter numbers: 1,2,3,4,5
15

可替换地:

>>> def sum_given():
...     return sum(int(i.strip()) for i in input("Enter numbers: ").split(','))
... 
>>> sum_given()
Enter numbers: 1,2,3,4,5
15