自动求和,无需重新输入 numbers/int 的解析号码列表,以白色 space 分隔

Auto sum without need to reenter the resolved numbers list of numbers/int separated by white space

我想知道如何获取由白色 space 分隔的较长的 numbers/int 列表,并在几行代码中计算出 total/sum。

我已经尝试调整(我是初学者,正在做教程)本网站上的一些代码用于手动输入整数然后总结,但我想通过一些简单的循环使用看到我可以粘贴或复制数字在顶端,然后在末尾有一个总和计算,而不需要将数字输入到某个框中。我得到了以下代码,我只是通过将 raw_input 更改为 Python 3 的输入来复制和修改这些代码,但它产生了框。我试图在顶部手动定义数字,但出现了一堆错误。

>>>mylist = input("Enter a list of numbers, SEPERATED by WHITE SPACE(3 5 66 etc.): ")
# now you can use the split method of strings to get a list
>>>mylist = mylist.split() # splits on white space by default
# to split on commas -> mylist.split(",")

# mylist will now look something like. A list of strings.
['1', '44', '56', '2'] # depending on input of course

# so now you can do
>>>total = sum(int(i) for i in mylist)
# converting each string to an int individually while summing as you go

上面的最后一行说 "summing as you go" 但我想在开头输入一次数据,而不是再次手动输入某个框,然后在最后求和。我想直接计算总和,而无需输入框。 我开始尝试输入由白色 space 分隔的数字列表作为字符串,但一无所获,并且在 map 函数

中出错

我假设你的意思是你想将列表分配给一个变量。

你通过 mylist = [1, 44, 56, 2] 做到这一点,其中 mylist 是整数 [1, 44, 56, 2]list 分配给的变量。

In [9]: mylist = [1, 44, 56, 2]                                                                                                                                                                         

In [10]: total = sum(i for i in mylist)                                                                                                                                                                 

In [11]: total                                                                                                                                                                                          
Out[11]: 103

您可以使用 "reduce" 函数将指定函数应用于列表中的所有元素。而且,它更快。

    from functools import reduce
    import operator

    yourStr = "1 44 56 2"
    print( reduce(operator.add,[int(i) for i in yourStr.split()]) )