2017-02-21 33 views
-1
list_example = "['0101612-0', '0101611-2', '0101610-4', '0101608-8', '0101607-0', '0101606-2', '0100786-3', '0100784-8', '0100783-0', '0100782-2', '0100781-4', '0100780-6', '0100779-8', '0100778-0', '0100777-2']" 

我想上面轉換成這樣:轉換帶引號的列表爲Python列表

list_example = ['0101612-0', '0101611-2', '0101610-4', '0101608-8', '0101607-0', '0101606-2', '0100786-3', '0100784-8', '0100783-0', '0100782-2', '0100781-4', '0100780-6', '0100779-8', '0100778-0', '0100777-2'] 

我嘗試以下操作:list_example = list_example.split(',')導致到:

["['0101612-0'", 
" '0101611-2'", 
" '0101610-4'", 
" '0101608-8'", 
" '0101607-0'", 
" '0101606-2'", 
" '0100786-3'", 
" '0100784-8'", 
" '0100783-0'", 
" '0100782-2'", 
" '0100781-4'", 
" '0100780-6'", 
" '0100779-8'", 
" '0100778-0'", 
" '0100777-2']"] 

這是凌亂從中提取值。

回答

2

您可以使用ast.literal_eval

>>> import ast 
>>> s = "['0101612-0', '0101611-2', '0101610-4', '0101608-8', '0101607-0', '0101606-2', '0100786-3', '0100784-8', '0100783-0', '0100782-2', '0100781-4', '0100780-6', '0100779-8', '0100778-0', '0100777-2']" 
>>> ast.literal_eval(s) 
['0101612-0', '0101611-2', '0101610-4', '0101608-8', '0101607-0', '0101606-2', '0100786-3', '0100784-8', '0100783-0', '0100782-2', '0100781-4', '0100780-6', '0100779-8', '0100778-0', '0100777-2'] 

您可以split & strip也做到這一點,但它有點複雜:

>>> [x.strip('\'') for x in s.strip('[]').split(', ')] 
['0101612-0', '0101611-2', '0101610-4', '0101608-8', '0101607-0', '0101606-2', '0100786-3', '0100784-8', '0100783-0', '0100782-2', '0100781-4', '0100780-6', '0100779-8', '0100778-0', '0100777-2'] 
+0

當您看到一個常見問題時,您可以投票將其作爲副本關閉。這有助於網站保持其質量並避免分散。 – TigerhawkT3

-1

最簡單的(也可能是最危險的)的方式來做到這一點是使用eval

my_list = eval(list_example) 

此代碼應該返回一個充滿字符串的列表對象。警告:請確保用戶不能在list_example內輸入任何惡意代碼!