要求在输入列表?
问题描述:
有没有办法将所有输入数字添加到列表中?要求在输入列表?
我的意思是这样的:
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)
答
您可以输入这样的数字在Python 2列表:
list_of_numbers = [input('Number 1:'), input('Number 2:'), input('Number 3:')]
答
您可以使用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()
。
+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 2 3',或'1,2,3'或'[1,2,3]' –
你使用的是什么版本的Python? 2.7会尝试将输入转换为类型。 –
@PeterWood OP代码中没有'input()'; – Psytho