开发者

accessing two or more list in a single for-loop

开发者 https://www.devze.com 2023-03-10 01:27 出处:网络
provided that I have two lists in same length, list_a, list_b. I can print they items in a single for loop as follows:

provided that I have two lists in same length, list_a, list_b.

I can print they items in a single for loop as follows:

for i in range(0, len(list_a)):
    print "%s %s" % (list_a[i], list_b[i])

is there any alternative and elegant way to do above mentioned 开发者_开发技巧task ?

I have tried

for a, b in list_a, list_b:
    print ""


You need zip():

for a, b in zip(list_a, list_b):
     # whatever

When the lists are long and you are using Python 2.x, you might prefer itertools.izip() to save some memory.


Or you also able to use the following statement to combine lists:

map(lambda x,y,z: (x,y,z), list_a, list_b, list_c)
0

精彩评论

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