2017-02-16 68 views
-1

我已經定義了一個需要3個參數的函數,其中一個參數必須是一個列表。 我發現的一種解決方案只有在列表由整數構成時纔有效,這不一定是這種情況(類型可以在同一列表中變化)。 如何請求用戶的列表類型輸入?例如:當輸入類似[1,2,3]的東西時,它被認爲是一個列表?如何在Python中請求用戶的列表輸入?

+3

閱讀有關[ast.literal_eval](https://docs.python.org/2/library/ast.html #ast.literal_eval) – dawg

+0

這個問題有什麼關係? –

+0

是一個問題:如何從用戶請求列表類型輸入? – gregory

回答

0

這裏有一種方法:

$ cat foo.py 
import sys 
input1 = sys.argv[1] 
input2 = sys.argv[2] 
print('Before\n-------') 
print('input1:{},type_of_input1:{}'.format(input1, type(input1))) 
print('input2:{},type_of_input2:{}'.format(input2, type(input2))) 
print('After\n-------') 
input1 = input1.split(' ') 
print('input1:{},type_of_input1:{}'.format(input1, type(input1))) 
print('input2:{},type_of_input2:{}'.format(input2, type(input2))) 
$ 

執行輸出

$ python foo.py 'foo bar' bat 
Before 
------- 
input1:foo bar,type_of_input1:<type 'str'> 
input2:bat,type_of_input2:<type 'str'> 
After 
------- 
input1:['foo', 'bar'],type_of_input1:<type 'list'> 
input2:bat,type_of_input2:<type 'str'> 
$ 
-1

如果你完全信任用戶的輸入,你可以只使用eval()。假設用戶輸入字符串[1, 2, 3]

x = input() # Python 3, use raw_input for Python 2 
y = eval(x) # Dangerous, don't use with untrusted input 

print(y) 
# [1, 2, 3] 

print(len(y)) 
# 3 

更新:

ast.literal_eval這裏是一個更好的選擇。

import ast 

x = input() # Python 3, use raw_input for Python 2 
y = ast.literal_eval(x) 

print(y) 
# [1, 2, 3] 

print(len(y)) 
# 3 
+1

'eval'是一個危險的想法...只是等待別人輸入'__import __( 「shutil」)。rmtree' – donkopotamus

+0

同意,這就是爲什麼我提到它在我的答案中是危險的。如果意圖是作者在本地交互式運行腳本,則不會比shell提示更危險。 – Scovetta

+0

但爲什麼在這種情況下建議'eval'而不是'ast.literal_eval'? – donkopotamus

0

保持簡單和安全使用input和輸入轉換成列表自己:

import re 
re.sub("[^\w]", " ", input('-->')).split() 
-->This is a string of words converted into a list 

output: 

['This', 'is', 'a', 'string', 'of', 'words', 'converted', 'into', 'a', 'list'] 

input是一個內置的:https://docs.python.org/3/library/functions.html#input

0

使用ast.literal_eval

import ast 
while True: 
    s=raw_input("Enter a list: ") 
    s=ast.literal_eval(s) 
    if not isinstance(s, list): 
     print "Nope! {} is a {}".format(s, type(s)) 
    else: 
     break 
print s 

如果你想選擇輸入元組(通過輸入1,2,3例如)所述用戶的n個添加tupleisinstance

import ast 
while True: 
    s=raw_input("Enter a list: ") 
    s=ast.literal_eval(s) 
    if not isinstance(s, (list, tuple)): 
     print "Nope! {} is a {}".format(s, type(s)) 
    else: 
     break 
相關問題