Get a list of numbers as input from the user

2018-12-31 05:54发布

I tried to use raw_input() to get a list of numbers, however with the code

numbers = raw_input()
print len(numbers)

the input [1,2,3] gives a result of 7, so I guess it interprets the input as if it were a string. Is there any direct way to make a list out of it? Maybe I could use re.findall to extract the integers, but if possible, I would prefer to use a more Pythonic solution.

16条回答
流年柔荑漫光年
2楼-- · 2018-12-31 06:23

You just need to typeraw_input().split() and the default split() is that values are split by a whitespace.

查看更多
何处买醉
3楼-- · 2018-12-31 06:24

Try this:

numbers = raw_input()
numberlist = list(numbers)
查看更多
裙下三千臣
4楼-- · 2018-12-31 06:26

You can use .split()

numbers = raw_input().split(",")
print len(numbers)

This will still give you strings, but it will be a list of strings.

If you need to map them to a type, use list comprehension:

numbers = [int(n, 10) for n in raw_input().split(",")]
print len(numbers)

If you want to be able to enter in any Python type and have it mapped automatically and you trust your users IMPLICITLY then you can use eval

查看更多
人气声优
5楼-- · 2018-12-31 06:32

try this one ,

n=int(raw_input("Enter length of the list"))
l1=[]
for i in range(n):
    a=raw_input()
    if(a.isdigit()):
        l1.insert(i,float(a)) #statement1
    else:
        l1.insert(i,a)        #statement2

If the element of the list is just a number the statement 1 will get executed and if it is a string then statement 2 will be executed. In the end you will have an list l1 as you needed.

查看更多
春风洒进眼中
6楼-- · 2018-12-31 06:32

You can still use your code but you will need to tweak it a bit. You can use the code for python 2.9 or less:

number = raw_input()
print number

If you use python 3 or higher you can use the code:

number = input()
print number
查看更多
情到深处是孤独
7楼-- · 2018-12-31 06:33

You can use this function (with int type only) ;)

def raw_inputList(yourComment):
     listSTR=raw_input(yourComment)     
     listSTR =listSTR[1:len(listSTR)-1]
     listT = listSTR.split(",")
     listEnd=[]
     for caseListT in listT:
          listEnd.append(int(caseListT))
     return listEnd

This function return your list (with int type) !

Example :

yourList=raw_inputList("Enter Your List please :")

If you enter

"[1,2,3]" 

then

yourList=[1,2,3]          
查看更多
登录 后发表回答