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

It is much easier to parse a list of numbers separated by spaces rather than trying to parse Python syntax:

Python 3:

s = input()
numbers = list(map(int, s.split()))

Python 2:

s = raw_input()
numbers = map(int, s.split())
查看更多
倾城一夜雪
3楼-- · 2018-12-31 06:37

Answer is trivial. try this.

x=input()

Suppose that [1,3,5,'aA','8as'] are given as the inputs

print len(x)

this gives an answer of 5

print x[3]

this gives 'aA'

查看更多
临风纵饮
4楼-- · 2018-12-31 06:39

In Python 3.x, use this.

a = [int(x) for x in input().split()]

Example

>>> a = [int(x) for x in input().split()]
3 4 5
>>> a
[3, 4, 5]
>>> 
查看更多
无与为乐者.
5楼-- · 2018-12-31 06:42
k = []
i = int(raw_input('enter the number of values in the list '))
l = 0
while l < i:
    p = raw_input('enter the string ')
    k.append(p)
    l= l+1


print "list is ", k
查看更多
登录 后发表回答