Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
912 views
in Technique[技术] by (71.8m points)

python: avoiding zip truncation of list

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
', u'104,507,100
', u'106,916,100
', u'99,870,100
'],
            [u'Cost of Revenue
',u'56,000,000
']
            ]

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

It only prints:

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

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
', u'Cost of Revenue
')
(u'Dec 31, 2012', u'104,507,100
', u'56,000,000
')
(u'Dec 31, 2011', u'106,916,100
', u'')
(u'Dec 31, 2010', u'99,870,100
', u'')

To describe inc_data above,

inc_data = [ [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
', u'Cost of Revenue
')
(u'Dec 31, 2012', u'104,507,100
', u'56,000,000
')
(u'Dec 31, 2011', u'106,916,100
', u'')
(u'Dec 31, 2010', u'99,870,100
', 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use 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
', u'104,507,100
', u'106,916,100
', u'99,870,100
'],
            [u'Cost of Revenue
',u'56,000,000
']
            ]

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


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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...