2015-10-07 81 views
-2

有沒有辦法將所有輸入數字添加到列表中?要求在輸入列表?

我的意思是這樣的:

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) 
+0

你能給例如輸入?它們是用空格還是逗號分隔,它是以'[',']'開頭還是以''結尾? '1 2 3',或'1,2,3'或'[1,2,3]' –

+0

你使用的是什麼版本的Python? 2.7會嘗試將輸入轉換爲類型。 –

+1

@PeterWood OP代碼中沒有'input()'; – Psytho

回答

1

您可以輸入這樣的數字在Python 2列表:

list_of_numbers = [input('Number 1:'), input('Number 2:'), input('Number 3:')] 
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()

+2

這是可行的,因爲逗號分隔值被評估爲元組,然後'列表'然後轉換爲列表。 –

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]