tags:

views:

116

answers:

4

So I have three lists:

['this', 'is', 'the', 'first', 'list']
[1, 2, 3, 4, 5]
[0.01, 0.2, 0.3, 0.04, 0.05]

Is there a way that would allow me to print the values in these lists in order by index?

e.g.

this, 1, 0.01 (all items at list[0])
is, 2, 0.2 (all items at list[1])
the, 3, 0.3 (all items at list[2])
first, 4, 0.04 (all items at list[3])
list, 5, 0.05 (all items at list[4])

The number of items in each list varies each time the script is run, but they always end up with the same number of values in the end. So, one time, the script could create three arrays with 30 items, another time, it could create only 15 values in each, etc.

+3  A: 

Use zip

for items in zip(L1, L2, L3):
    print items

items will be a tuple with a value from each list, in order.

truppo
+6  A: 

What you are probably looking for is called zip:

>>> x = ['this', 'is', 'the', 'first', 'list']
>>> y = [1, 2, 3, 4, 5]
>>> z = [0.01, 0.2, 0.3, 0.04, 0.05]
>>> zip(x,y,z)
[('this', 1, 0.01), ('is', 2, 0.20000000000000001), ('the', 3, 0.29999999999999999), ('first', 4, 0.040000000000000001), ('list', 5, 0.050000000000000003)]
>>> for (a,b,c) in zip(x,y,z):
...     print a, b, c
... 
this 1 0.01
is 2 0.2
the 3 0.3
first 4 0.04
list 5 0.05
Jack Lloyd
Also to be mentioned: itertools.izip, that creates a generator for the result.
RaphaelSP
Thanks! works like a charm! Formats nicely and everything.
steve
A: 
lists = ( ['this', 'is', 'the', 'first', 'list'], 
          [1, 2, 3, 4, 5], 
          [0.01, 0.2, 0.3, 0.04, 0.05])
print zip(*lists)

zips the lists together and stops when the shortest list runs out of items.

THC4k
A: 

This is the most immediately obvious way (to a python newb), and there is likely a better way, but here goes:

#Your list of lists.
uberlist = ( list1, list2, list3 )

#No sense in duplicating this definition multiple times.
#Define it up front.
uberRange = range( len( uberList ) );

#Since each will be the same length, you can use one range.
for i in range( len( list1 ) ):
    # Iterate through the sub lists.
    for j in uberRange:
        #Output
        print uberlist[ j ][ i ];
Christopher W. Allen-Poole
Although your solution works, zip is more pythonic (and shorter).
RaphaelSP
Yea, I'm not surprised that there is a better way. I've only been looking at Python for a few weeks (if that), so I'm sure that most of my attempts will still be the "long way around".
Christopher W. Allen-Poole
I'll also wager that zip is faster: my answer was written in Python, zip is a build-in method.
Christopher W. Allen-Poole
It's really hard to overstate how important `zip` is, especially used in conjunction with other language elements that work with tuples. For instance, it's not obvious what `x = dict(zip(keys, values))` is doing when you're first learning Python, but it's an essential idiom.
Robert Rossney
you can also unzip with zip itself `keys, values == zip(*zip(keys, values))`
kaizer.se