2014-04-05 112 views
0

我只有一個元素的列表,它本身就是一個元素列表。Python:將字符串分割成元素並將它們添加到列表中

str = '"MARY","PATRICIA","LINDA","BARBARA","ELIZABETH","JENNIFER","MARIA","SUSAN","MARGARET","DOROTHY","LISA","NANCY","KAREN","BETTY","HELEN","SANDRA","DONNA","CAROL"' 

現在,我希望該字符串中的每個單獨名稱都包含在另一個列表中。爲此,我明白我必須單獨分割每個名稱,然後將它們附加到所需的列表中。這裏是我寫的代碼相同:

str = '"MARY","PATRICIA","LINDA","BARBARA","ELIZABETH","JENNIFER","MARIA","SUSAN","MARGARET","DOROTHY","LISA","NANCY","KAREN","BETTY","HELEN","SANDRA","DONNA","CAROL"' 
li = str.split() 
c = li[0] 
ip = [] 
start = c.find('"') 
final = c.find('"', start+1) 
def iter(start, final): 
    e = c[start+1:final] 
    ip.append(e) 
nstart = c.find('"', final+1) 
nfinal = c.find('"', nstart+1) 
if(nstart == -1 or nfinal == -1): 
    print ip 
else: 
    iter(nstart, nfinal) 

但是,我沒有得到任何輸出。 'ip'是我打算單獨存儲所有名稱的列表。我的代碼似乎有什麼問題?

+4

'名稱列表= nameStr的[1:-1] .split( ' 「」')'? – Hyperboreus

+0

這個字符串從哪裏來的?這看起來很像一行CSV文件。 – DSM

+0

我從我正在使用的文件中獲得該字符串。 –

回答

2

您的代碼比需要的要複雜得多。您可以使用評論,或做:

foo = '"MARY","PATRICIA","LINDA","BARBARA","ELIZABETH","JENNIFER","MARIA","SUSAN","MARGARET","DOROTHY","LISA","NANCY","KAREN","BETTY","HELEN","SANDRA","DONNA","CAROL"' 
output = foo.replace('"','').split(",") 
2

首先,調用str是不好的,因爲str是python中的內建函數。

其次,你可以用下面這樣做:

in_list_string = '"MARY","PATRICIA","LINDA","BARBARA","ELIZABETH","JENNIFER","MARIA","SUSAN","MARGARET","DOROTHY","LISA","NANCY","KAREN","BETTY","HELEN","SANDRA","DONNA","CAROL"' 
out_list= [element.strip('"') for element in in_list_string.split(',')] 
2

使用the csv module爲CSV數據:

>>> import csv 
>>> from StringIO import StringIO 
>>> dont_call_me_str='"MARY","PATRICIA","LINDA","BARBARA","ELIZABETH","JENNIFER","MARIA","SUSAN","MARGARET","DOROTHY","LISA","NANCY","KAREN","BETTY","HELEN","SANDRA","DONNA","CAROL"' 
>>> list(csv.reader(StringIO(dont_call_me_str))) 
[['MARY', 'PATRICIA', 'LINDA', 'BARBARA', 'ELIZABETH', 'JENNIFER', 'MARIA', 'SUSAN', 'MARGARET', 'DOROTHY', 'LISA', 'NANCY', 'KAREN', 'BETTY', 'HELEN', 'SANDRA', 'DONNA', 'CAROL']] 
相關問題