python:避免列表的zip截断

时间:2013-10-26 05:19:36

标签: python list truncation

我有以下使用zip()的python代码,它似乎会导致意外的数据截断。

inc_data = [[u'Period Ending', u'Dec 31, 2012', u'Dec 31, 2011', u'Dec 31, 2010'],
            [u'Total Revenue\n', u'104,507,100\n', u'106,916,100\n', u'99,870,100\n'],
            [u'Cost of Revenue\n',u'56,000,000\n']
            ]

inc_data2 = zip(*inc_data)
for i in inc_data2:
    print i

它只打印:

(u'Period Ending', u'Total Revenue\n', u'Cost of Revenue\n')
(u'Dec 31, 2012', u'104,507,100\n', u'56,000,000\n')

但是我希望它打印以下内容,但显然我必须手动添加填充程序u''以防止zip()截断inc_data。但我不知道如何编码。

(u'Period Ending', u'Total Revenue\n', u'Cost of Revenue\n')
(u'Dec 31, 2012', u'104,507,100\n', u'56,000,000\n')
(u'Dec 31, 2011', u'106,916,100\n', u'')
(u'Dec 31, 2010', u'99,870,100\n', u'')

要描述上面的inc_data,

inc_data = [ [x],
             [y],
             [z] ]   

如何使x,y和z长度相同?长度是x,y或z的最大长度?

(u'Period Ending', u'Total Revenue\n', u'Cost of Revenue\n')
(u'Dec 31, 2012', u'104,507,100\n', u'56,000,000\n')
(u'Dec 31, 2011', u'106,916,100\n', u'')
(u'Dec 31, 2010', u'99,870,100\n', u'')

对于问题的冗长而冗长的解释感到抱歉。你能帮助我或指出一个已经回答过的类似问题吗?非常感谢!

1 个答案:

答案 0 :(得分:17)

使用izip_longest

from itertools import izip_longest

inc_data = [[u'Period Ending', u'Dec 31, 2012', u'Dec 31, 2011', u'Dec 31, 2010'],
            [u'Total Revenue\n', u'104,507,100\n', u'106,916,100\n', u'99,870,100\n'],
            [u'Cost of Revenue\n',u'56,000,000\n']
            ]

print list(izip_longest(*inc_data, fillvalue=u'')) 


# [(u'Period Ending', u'Total Revenue\n', u'Cost of Revenue\n'), 
   (u'Dec 31, 2012', u'104,507,100\n', u'56,000,000\n'), 
   (u'Dec 31, 2011', u'106,916,100\n', u''), 
   (u'Dec 31, 2010', u'99,870,100\n', u'')]