在转换为列表时,如何防止Python将双位整数拆分为两个单个整数

时间:2015-11-11 01:46:54

标签: python list sum

我的任务是编写一个脚本,让用户输入一个数字列表,并让脚本在该列表中添加每个数字以获得总和。我能够编写脚本,但是当我输入一个多于一位的整数时,我遇到了麻烦。这是我的代码和工作脚本:

#!/usr/bin/python

#Sum of integers in a list

#Takes input and removes non-number characters

nList = input("please enter a list of integers separated by commas:\n")
n = ""
numList1 = list(n.join((i) for i in nList if i.isalnum())) #Converts into list of Strings
numList = list(map(int, numList1))#Converts list of strings into a list of integers
print(numList) #prints the numList

#Takes list and adds all the numbers together

def sumArg(numList):
    nSum= map(int, numList) #converts list into individual integers
    numSum = sum(i for i in nSum) #adds the integers together
    print(numSum)#prints the sum

sumArg(numList) #runs script

当我运行脚本并输入(1,2,3,4,5,6,7,8,9)时,它会打印出来

[1, 2, 3, 4, 5, 6, 7, 8, 9]
45

但是当我将数字10添加到列表的末尾时,我将其作为输出

[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0]
46

我知道数字1到10的总和等于55,而不是46。有没有办法让我编写这个脚本而不用Python将10转为1,0。我希望能够让用户输入任何类型的整数,并打印出正确的总和。

5 个答案:

答案 0 :(得分:2)

你不应该将逗号分隔的字符串转换成这样的整数。特别是你的算法通过删除所有逗号来启动进程,这使得无法从下一个数字中分辨出一个数字。

相反,使用str.split()简单地将字符串拆分为给定分隔符上的list

nList = input("please enter a list of integers separated by commas:\n")
nList = map(int, nList.split(','))

此外,您可以使用内置的sum()函数找到此map对象的总和(无需将其转换为list):

total = sum(nList)

答案 1 :(得分:0)

  1. 在此使用str.split()
  2. 我认为使用return代替print是一个好主意。
  3. nList = input("please enter a list of integers separated by commas:\n")
    numList = nList.split(',')
    
    def sumArg(numList):
        nSum= map(int, numList)
        numSum = sum(nSum)
        return numSum
    
    print(numList)    
    print(sumArg(numList))
    

    演示:

    please enter a list of integers separated by commas:
    1,2,3,4,5,6,7,8,9,10,120
    ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '120']
    175
    

答案 2 :(得分:0)

以下是您更正后的代码:

nList = input("please enter a list of integers separated by commas:\n")

# Converts into list of Strings
numList1 = nList.split(',')
print(numList1)
numList = list(map(int, numList1))
print(numList)


def sumArg(numList):
     print(sum(numList))

sumArg(numList)  # runs script

问题是你的numList1 = list(n.join((i) for i in nList if i.isalnum()))正在扫描每个角色。我上面发布的代码将数组拆分为每个逗号,将数字转换为整数并将它们相加。

答案 3 :(得分:0)

nList = input("please enter a list of integers separated by commas:\n")

nList是一个字符串,字符串是字符序列

(i) for i in nList

在这里,您将遍历处理每个字符的字符串。你将每个字符分开,这就是“10”变为“1”和“0”的原因。

由于您输入的每个数字都以逗号分隔,请尝试在逗号上拆分。

numList1 = nList.split(",")

如果输入也被括号括起来,那么在转换为int之前你需要删除它们。

答案 4 :(得分:0)

实际上,如果您使用的是Python 2,那么您的脚本可以归结为:

nList = input("please enter a list of integers separated by commas:\n")
print sum(nList)

这是因为Python 2中的input已经将字符串的输入转换为整数列表。

如果要将字符串作为输入,然后将其转换为整数列表,则可以使用raw_input(或Python 3中的input):

inputStr = raw_input("please enter a list of integers separated by commas:\n")
listOfStrs = inputStr.split(",")
listOfInts = map(int, listOfStrs)
print sum(listOfInts)

这需要像1, 2, 3, 4, 5, 6, 7, 8, 9, 10这样的输入(没有括号)。

相关问题