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

Another way could be to use the for-loop for this one. Let's say you want user to input 10 numbers into a list named "memo"

memo=[] 
for i in range (10):
    x=int(input("enter no. \n")) 
    memo.insert(i,x)
    i+=1
print(memo) 
查看更多
谁念西风独自凉
3楼-- · 2018-12-31 06:16

try this

numbers = raw_input()
a = numbers.split(" ")
查看更多
旧时光的记忆
4楼-- · 2018-12-31 06:17
num = int(input('Size of elements : '))
arr = list()

for i in range(num) :
  ele  = int(input())
  arr.append(ele)

print(arr)
查看更多
大哥的爱人
5楼-- · 2018-12-31 06:20

eval(a_string) evaluates a string as Python code. Obviously this is not particularly safe. You can get safer (more restricted) evaluation by using the literal_eval function from the ast module.

raw_input() is called that in Python 2.x because it gets raw, not "interpreted" input. input() interprets the input, i.e. is equivalent to eval(raw_input()).

In Python 3.x, input() does what raw_input() used to do, and you must evaluate the contents manually if that's what you want (i.e. eval(input())).

查看更多
呛了眼睛熬了心
6楼-- · 2018-12-31 06:22
a=[]
b=int(input())
for i in range(b):
    c=int(input())
    a.append(c)

The above code snippets is easy method to get values from the user.

查看更多
宁负流年不负卿
7楼-- · 2018-12-31 06:22

you can pass a string representation of the list to json:

import json

str_list = raw_input("Enter in a list: ")
my_list = json.loads(str_list)

user enters in the list as you would in python: [2, 34, 5.6, 90]

查看更多
登录 后发表回答