2014-07-25 46 views
0

,比如我有以下列表:分割清單,等於內容

contents= ["i have two pens","prices = 5$","made in ____ and ____"] 

我想分割他們這樣一種方式,它具有相同的內容如下:

array[0]= ["i", "have", "two", "pens", ""] 
array[1]= ["prices", "=", "5$", " ", " "] 
array[2]= ["made", "in", "____", "and" ,"____"] 

這意味着,每個數組有相同數量的內容(這裏是5)。我正在使用的代碼是:

array = [phrase.split() for phrase in contents] 

但確實,它不會將它們拆分爲相同的內容。任何人都可以建議我如何解決這個使用python?

+2

你能解釋一下爲什麼你想要這個;這可能是一個XY問題。例如,'itertools.izip_longest'可以解決它而不會干擾分割。 – jonrsharpe

+0

因爲我想使用循環。我只有一個數組中的內容(例如array [5])。所以當它迭代array [i] [1]時,它會得到錯誤「IndexError:list index out of range」,因爲沒有array [5] [1]。 –

+0

不是我期望的更廣泛的觀點,但它看起來像:您想要同時遍歷所有列表,查看每個元素中的第i個元素,但需要填充較短的列表。 [以此步驟](https://docs.python.org/2/library/itertools.html#itertools.izip_longest)。 – jonrsharpe

回答

1

你需要檢查這是最長的數組,然後墊其他的人,像這樣的:

array = [phrase.split() for phrase in contents] 
x = max(len(i) for i in array) 
result = [i + [''] * (x - len(i)) for i in array] 

複雜,但給你你正在尋找的結果。

+1

我懷疑'itertools.izip_longest'實際上是OP在這裏尋找的。 –

1

這是另一種選擇,可能也很複雜。

from itertools import izip_longest 

array = [phrase.split() for phrase in contents] 
l = izip_longest(*array, fillvalue=u'') 
result = [list(t) for t in zip(*l)] 
+0

感謝您的幫助... –

+0

@genocide_in_hell http://stackoverflow.com/help/someone-answers – jonrsharpe

1

快速演示,以擴大我的意見,使用izip_longest from itertools

>>> from itertools import izip_longest 
>>> contents = ["i have two pens", 
       "prices = 5$", 
       "made in ____ and ____"] 
>>> array = [phrase.split() for phrase in contents] 
>>> for t in izip_longest(*array, fillvalue=" "): 
     print t 


('i', 'prices', 'made') 
('have', '=', 'in') 
('two', '5$', '____') 
('pens', ' ', 'and') 
(' ', ' ', '____') 

,你遍歷子列表你並不需要修改array,這片給你。