2016-04-18 74 views
0

我有一個列表和一個for循環:Python的 - 列表和循環

myList = [「aa,bb,cc,dd」, 「ee,ff,gg,hh」] 

for item in myList: 
    print (「x: %s」 % item) 

輸出看起來像:

x: aa,bb,cc,dd 
x: ee,ff,gg,hh 

我所需的輸出是:

x: aa 
    bb 
    cc 
    dd 

x: ee 
    ff 
    gg 
    hh 

回答

1

你可以使用splitjoin功能非常無縫

>>> myList = ["aa,bb,cc,dd", "ee,ff,gg,hh"] 
>>> for item in myList: 
...  print("x: %s" % "\n ".join(item.split(","))) 
... 
x: aa 
    bb 
    cc 
    dd 
x: ee 
    ff 
    gg 
    hh 

split拆分字符串分解成你作爲一個參數傳遞的分隔符列表,join將加入名單成一個字符串,用你把它作爲一個木匠的字符串。

另一種選擇是隻使用替換:

>>> for item in myList: 
...  print("x: %s" % item.replace(",", "\n ")) 
... 
x: aa 
    bb 
    cc 
    dd 
x: ee 
    ff 
    gg 
    hh 
+0

謝謝!!!!!和+10的解釋:) – Matthew

+0

任何時候都沒問題! –

0

+1答案above..Another方式看起來是這樣的:

myList = ["aa,bb,cc,dd", "ee,ff,gg,hh"] 

for item in myList: 
    first, *rest = item.split(",") 
    print ("x: %s" %first) 
    for r in rest: 
     print (" %s" %r)