python:避免列表的zip截断 [英] python: avoiding zip truncation of list

查看:113
本文介绍了python:避免列表的zip截断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following python code that uses zip() and it seems to cause unintended data truncation.

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.但是我不知道该怎么编码.

But I want it to print the following, but apparently I have to add in fillers u'' by hand in order to prevent zip() from truncating the inc_data. But I don't know how to code that.

(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,

To describe inc_data above,

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

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

How do I make x, y and z to be the same length? And the length is the max length of x, y, or 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'')

很抱歉,这个问题冗长冗长.如果存在的话,您能帮我还是指出一个已经回答的类似问题?非常感谢!

Sorry for the lengthy and wordy explanation of the problem. Could you help me or point me to a similar question that has been answered, if one exists? many thanks!

推荐答案

使用 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'')]

这篇关于python:避免列表的zip截断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆