Python 使用 input() 列出的数字/数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14177582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:40:21  来源:igfitidea点击:

number/numbers to list by using input()

pythonlistinputnumbers

提问by

Maybe this is a very basic question but i am a beginner in python and couldnt find any solution. i was writing a python script and got stuck because i cant use python lists effective. i want user to input (number or numbers) and store them in a python list as integers. for example user can input single number 1 or multiple numbers seperated by comma 1,2,3 and i want to save them to a list in integers. i tried this ;

也许这是一个非常基本的问题,但我是 python 的初学者,找不到任何解决方案。我正在编写一个 python 脚本并且卡住了,因为我不能有效地使用 python 列表。我希望用户输入(数字或数字)并将它们作为整数存储在 python 列表中。例如,用户可以输入单个数字 1 或由逗号 1,2,3 分隔的多个数字,我想将它们保存到整数列表中。我试过这个;

def inputnumber():
    number =[]
    num = input();
    number.append(num)
    number = map(int,number)
return (number)
def main():
    x = inputnumber()
print x

for a single number there is no problem but if the the input is like 1,2,3 it gives an error:

对于单个数字没有问题,但如果输入类似于 1,2,3,则会出现错误:

Traceback (most recent call last):
File "test.py", line 26, in <module>
main()
File "test.py", line 21, in main
x = inputnumber()
File "test.py", line 16, in inputnumber
number = map(int,number)
TypeError: int() argument must be a string or a number, not 'tuple'

Also i have to take into account that user may input characters instead of numbers too. i have to filter this. if the user input a word a single char. i know that i must use try: except. but couldn't handle. i searched the stackoverflow and the internet but in the examples that i found the input wanted from user was like;

另外我必须考虑到用户也可能输入字符而不是数字。我必须过滤这个。如果用户输入一个单词单个字符。我知道我必须使用 try: except。但无法处理。我搜索了 stackoverflow 和互联网,但在示例中,我发现用户想要的输入是这样的;

>>>[1,2,3]

i found something this Mark Byers's answerin stackoverflow but couldn't make it work i use python 2.5 in windows.

我在 stackoverflow 中找到了Mark Byers 的答案,但无法使其工作,我在 Windows 中使用 python 2.5。

Sorry for my English. Thank you so much for your helps.

对不起我的英语不好。非常感谢您的帮助。

采纳答案by RocketDonkey

In your function, you can directly convert numinto a list by calling split(','), which will split on a comma - in the case a comma doesn't exist, you just get a single-element list. For example:

在您的函数中,您可以num通过调用直接转换为列表split(','),这将在逗号上拆分 - 在逗号不存在的情况下,您只会得到一个单元素列表。例如:

In [1]: num = '1'

In [2]: num.split(',')
Out[2]: ['1']

In [3]: num = '1,2,3,4'

In [4]: num.split(',')
Out[4]: ['1', '2', '3', '4']

You can then use your function as you have it:

然后,您可以使用您拥有的功能:

def inputnumber():
    num = raw_input('Enter number(s): ').split(',')
    number = map(int,num)
    return number

x = inputnumber()
print x

However you can take it a step further if you want - maphere can be replaced by a list comprehension, and you can also get rid of the intermediate variable numberand return the result of the comprehension (same would work for mapas well, if you want to keep that):

但是,如果您愿意,您可以更进一步 -map此处可以替换为列表推导式,您还可以摆脱中间变量number并返回推导式的结果(map如果您想,同样适用保持那个):

def inputnumber():
    num = raw_input('Enter number(s): ').split(',')
    return [int(n) for n in num]

x = inputnumber()
print x

If you want to handle other types of input without error, you can use a try/exceptblock (and handle the ValueErrorexception), or use one of the fun methods on strings to check if the number is a digit:

如果您想处理其他类型的输入而不会出错,您可以使用try/except块(并处理ValueError异常),或使用字符串上的一种有趣方法来检查数字是否为数字:

def inputnumber():
    num = raw_input('Enter number(s): ').split(',')
    return [int(n) for n in num if n.isdigit()]

x = inputnumber()
print x

This shows some of the power of a list comprehension - here we say 'cast this value as an integer, but only if it is a digit (that is the if n.isdigit()part).

这显示了列表推导式的一些威力——这里我们说'将此值转换为整数,但前提是它是一个数字(即if n.isdigit()部分)。

And as you may have guessed, you can collapse it even more by getting rid of the function entirely and just making it a one-liner (this is an awesome/tricky feature of Python - condensing to one-liners is surprisingly easy, but can lead to less readable code in some case, so I vote for your approach above :) ):

正如您可能已经猜到的那样,您可以通过完全摆脱函数并使其成为单行代码来进一步折叠它(这是 Python 的一个很棒/棘手的功能 - 压缩为单行代码非常容易,但可以在某些情况下会导致代码可读性降低,所以我投票支持你上面的方法:)):

print [int(n) for n in raw_input('Number(s): ').split(',') if n.isdigit()]

回答by Volatility

inputis not the way to go here - it evaluates the input as python code. Use raw_inputinstead, which returns a string. So what you want is this:

input不是去这里的方法 - 它将输入评估为 python 代码。使用raw_input替代,它返回一个字符串。所以你想要的是这个:

def inputnumber():
    num = raw_input()
    for i, j in enumerate(num):
        if j not in ', ':
            try:
                int(num[i])
            except ValueError:
                #error handling goes here
    return num

def main():
    x = inputnumber()
    print x

I guess all it is is a long-winded version of RocketDonkey's answer.

我想这只是 RocketDonkey 答案的冗长版本。