开发者

Dynamically decompose list into variables in Python

I have 2 dimensional list created at runtime (the number of entries in either dimension is unknown).开发者_运维技巧 For example:

long_list = [ [2, 3, 6], [3, 7, 9] ]

I want to iterate through it by getting the ith entry from each list inside the long_list:

for entry in long_list.iter():
    #entry will be [2, 3] then [3, 7] then [6, 9]

I know that Python's itertools.izip_longest() method does this. Except it takes in a different variable for each list.

itertools.izip_longest(var1, var2, var3 ...)

So, how do I split my long_list into a different variable for each list and then call izip_longest() with all those variable at runtime?


>>> long_list = [ [2, 3, 6], [3, 7, 9] ]
>>> import itertools
>>> for i in itertools.izip_longest(*long_list):      # called zip_longest in py3k
    print(i)


(2, 3)
(3, 7)
(6, 9)

Basically, you need to use unpacking feature here. It would work similarly for zip.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜