Reputation: 11
for example I have the following list:
contents= ["i have two pens","prices = 5$","made in ____ and ____"]
I want to split them such a way that it has the same content as following:
array[0]= ["i", "have", "two", "pens", ""]
array[1]= ["prices", "=", "5$", " ", " "]
array[2]= ["made", "in", "____", "and" ,"____"]
that means, each array has equal number of contents (5 here). The code I am using is:
array = [phrase.split() for phrase in contents]
but surely, it doesn't split them with equal contents. Can anyone suggest me how can I solve this using python?
Upvotes: 0
Views: 100
Reputation: 122105
A quick demo to expand on my comment, using 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')
(' ', ' ', '____')
You don't need to modify array
, this pads for you as you iterate over the sublists.
Upvotes: 1
Reputation: 601
This is another choice, May be also complicated.
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)]
Upvotes: 1
Reputation: 7067
You would need to check which is the longest array and then pad the other ones, like this:
array = [phrase.split() for phrase in contents]
x = max(len(i) for i in array)
result = [i + [''] * (x - len(i)) for i in array]
Complicated but gives you the result you're looking for.
Upvotes: 1