accessing two or more list in a single for-loop
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)
精彩评论