要求输入列表?

时间:2015-10-07 09:47:17

标签: python

有没有办法将所有输入数字添加到列表中?

我是这样的意思:

 input = ("Type in a list of numbers") e.g [2,-3,5,6,-1]

然后将所有这些数字都列入一个列表?

我想也许是这样,但它不起作用,

input = ("Type in a list of numbers")
ls = []

ls.append(input)

3 个答案:

答案 0 :(得分:2)

Python 2.7将起作用:

>>> input() # [1, 2, 3]
[1, 2, 3]

>>> type(_)
list

Python 3:

>>> import ast
>>> ast.literal_eval(input()) # [1, 2, 3]
[1, 2, 3]

答案 1 :(得分:1)

您可以在Python 2中输入这样的数字列表:

list_of_numbers = [input('Number 1:'), input('Number 2:'), input('Number 3:')]

答案 2 :(得分:0)

您可以使用ast.literal_eval来解析用户输入的数字列表:

import ast

numbers = input('Type in a list of numbers, separated by comma:\n')

lst = list(ast.literal_eval(numbers)))

print('You entered the following list of numbers:')
print(lst)
Type in a list of numbers, separated by comma:
1, 523, 235235, 34645, 56756, 21124, 346346, 658568, 123123, 345, 2
You entered the following list of numbers:
[1, 523, 235235, 34645, 56756, 21124, 346346, 658568, 123123, 345, 2]

请注意,使用Python 2,您需要使用raw_input()而不只是input()