number/numbers to list by using input() [duplicate]

情到浓时终转凉″ 提交于 2020-01-24 12:59:08

问题


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

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'

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]

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.


回答1:


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

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

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

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

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()]



回答2:


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

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.



来源:https://stackoverflow.com/questions/14177582/number-numbers-to-list-by-using-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!