9

我有以下使用 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'')

很抱歉对问题进行了冗长而冗长的解释。你能帮我或指出一个已经回答的类似问题,如果存在的话?非常感谢!

4

1 回答 1

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'')]
于 2013-10-26T05:22:24.060 回答