2013-06-26 46 views
1

我有一個string這樣Python字符串列出轉換

sample="[2, 6, 10, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50]" 

如何轉換,爲list?我期待的輸出爲列表,這樣

output=[2, 6, 10, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50] 

我知道split()功能,但在這種情況下,如果我使用

sample.split(',') 

它會在[]符號。有沒有簡單的方法來做到這一點?

編輯對不起,重複post..I沒有看到這個帖子到現在爲止 Converting a string that represents a list, into an actual list object

+1

'輸出= json.loads(樣品)'? – geoffspear

回答

1

,你可以使用標準的字符串方法與Python:如果你使用.split(',')代替

output = sample.lstrip('[').rstrip(']').split(', ') 

.split(',')您將獲得空間與價值!

你可以轉換所有值利用爲int:

output = map(lambda x: int(x), output) 

或加載字符串作爲JSON:

import json 
output = json.loads(sample) 

作爲一個令人高興的巧合,JSON列表有相同的符號作爲Python列表! :-)

+0

非常感謝!直到現在我還不知道'lstrip'和'rstrip' ..非常有用的東西。 –

+0

@ChrisAung實際上調用'sample.strip('[]')'相當於'sample.lstrip('[')。rstrip(']')'。大多數具有'r'和'l'版本的方法也有一個沒有前綴的版本,可以在字符串的兩端工作。 – Bakuriu

+0

@Bakuriu你說得對,但我更喜歡在可以的時候明確表示,這樣一個不是格式良好的列表就會中斷。顯式優於隱式;-)。 – zmo

4

如果你將要處理與Python式的類型(如元組爲例),你可以使用ast.literal_eval

from ast import literal_eval 

sample="[2, 6, 10, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50]" 

sample_list = literal_eval(sample) 
print type(sample_list), type(sample_list[0]), sample_list 
# <type 'list'> <type 'int'> [2, 6, 10, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50] 
+0

不錯,Jon,我不知道'ast.literal_eval' – zmo