使用input()列出的一个或多个数字 [英] number/numbers to list by using input()

查看:129
本文介绍了使用input()列出的一个或多个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 ;

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

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

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

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'

我还必须考虑到用户也可以输入字符而不是数字.我必须对此进行过滤.如果用户输入一个单词一个字符.我知道我必须使用try:除外.但无法处理.我搜索了stackoverflow和互联网,但在示例中,我发现用户想要的输入就像;

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;

>>>[1,2,3]

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

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

对不起,我的英语.非常感谢您的帮助.

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

推荐答案

在您的函数中,您可以通过调用split(',')直接将num转换为列表,该列表将以逗号分隔-如果逗号没有不存在,您只会得到一个单元素列表.例如:

In your function, you can directly convert num into 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:

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

但是,如果需要,您可以更进一步-map可以用列表推导代替,也可以摆脱中间变量number并返回推导的结果(相同如果您想保留map,也可以使用它):

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

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

x = inputnumber()
print x

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

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

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

x = inputnumber()
print x

这显示了列表理解的某些功能-在这里我们说将这个值转换为整数,但前提是它是一个数字(即if n.isdigit()部分).

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

您可能已经猜到了,您可以通过完全放弃该功能并将其变成单线来进一步折叠它(这是Python的一个很棒/精妙的功能-浓缩为单线非常容易,但是在某些情况下可能会导致代码的可读性降低,因此,我在上面为您的方法投了赞成票:)):

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

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

这篇关于使用input()列出的一个或多个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆