8
votes

I'm a bit of a Python beginner so I apologise if this is a very basic question.

I have two lists of data which are obtained from:

with filein as f:
        reader=csv.reader(f)
        xs, ys = zip(*reader)

I would like to create a loop which would take the first item in "xs" and the first item in "ys" and print them out. I would then like to loop back and repeat for the second item in both lists and so forth.

I had thought something like:

for x in xs and y in ys:

Or

for x in xs:
    for y in ys:

But neither of these seems to give the desired result.

3

3 Answers

14
votes

Use the zip function, along with tuple unpacking:

for x, y in zip(xs, ys):
    print x, y

In your case, depending on what you need the xs and ys for, you could have iterated through the csv.reader directly:

with filein as f:
    reader=csv.reader(f)
    for x, y in reader:
        print x, y

The zip(xs, ys) line was effectively reversing your xs, ys = zip(*reader) line.

6
votes

Use zip:

>>> L=[1,2,3]
>>> M=[4,5,6]
>>> for a,b in zip(L,M):
...   print(a,b)
...
1 4
2 5
3 6
0
votes

For a one line you can use combination of map() and lambda(). Look here if not familiar to this concepts.

But be careful, you must be with python 3.x so that print is a function and can be used inside the lambda expression.

>>> from __future__ import print_function
>>> l1 = [2,3,4,5]
>>> l2 = [6,7,3,8]
>>> list(map(lambda X: print(X[0],X[1]), list(zip(l1,l2))))

output

2 6
3 7
4 3
5 8