splitting list with equal contents

后端 未结 3 977
慢半拍i
慢半拍i 2021-01-28 05:40

for example I have the following list:

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

I want to split them such a wa

相关标签:
3条回答
  • 2021-01-28 05:51

    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)]
    
    0 讨论(0)
  • 2021-01-28 06:14

    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.

    0 讨论(0)
  • 2021-01-28 06:18

    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.

    0 讨论(0)
提交回复
热议问题