gdogg371
gdogg371

Reputation: 4152

Zipping multiple lists together?

I have the following code:

zero = ('one','two','three','four')

one   = '1.0,4.5,5.5,*,2.5,2.8,5.3,*,1.75,4.0,5.75,*,1.0,4.1,5.1,*,2.25,4.75,7.0,*,2.2,5.4,7.6,*,3.0,3.0,6.0,*,1.2,3.55,4.75,*,1.5,4.66666666667,6.16666666667,*,2.0,3.0,5.0,*,1.5,4.33333333333,5.83333333333,*,2.33333333333,2.8,5.13333333333,*,1.5,4.0,5.5,*,1.0,4.66666666667,5.66666666667,*,1.5,3.0,4.5,*,2.5,3.5,6.0,*,1.33333333333,3.4,4.73333333333,*,2.0,3.0,5.0,*,1.5,2.2,3.7,*,3.0,2.7,5.7,*,'
two   = '2.8,*,2.6,*,3.66666666667,*,4.0,*,1.5,*,2.16666666667,*,2.2,*,2.5,*,2.83333333333,*,2.8,*,2.83333333333,*,2.0,*,1.75,*,3.0,*,3.0,*,1.4,*,3.75,*,1.6,*,3.5,*,2.8,*,'

test = one, two = one.split("*,"),two.split("*,")
print test
print("\n".join("".join(x) for x in zip(one,two)))

This allows me to zip together my two lists to get an output that looks like this:

1.0,4.5,5.5,2.8,
2.5,2.8,5.3,2.6,
1.75,4.0,5.75,3.66666666667,
1.0,4.1,5.1,4.0,
2.25,4.75,7.0,1.5,
2.2,5.4,7.6,2.16666666667,
3.0,3.0,6.0,2.2,
1.2,3.55,4.75,2.5,
1.5,4.66666666667,6.16666666667,2.83333333333,
2.0,3.0,5.0,2.8,
1.5,4.33333333333,5.83333333333,2.83333333333,
2.33333333333,2.8,5.13333333333,2.0,
1.5,4.0,5.5,1.75,
1.0,4.66666666667,5.66666666667,3.0,
1.5,3.0,4.5,3.0,
2.5,3.5,6.0,1.4,
1.33333333333,3.4,4.73333333333,3.75,
2.0,3.0,5.0,1.6,
1.5,2.2,3.7,3.5,
3.0,2.7,5.7,2.8,

I have been trying a few different approaches to using a for loop to zip many lists together, but I'm not having any luck. Is zipping more than two lists together at once even possible, or is there a better way of achieving what I want?

Thanks

Upvotes: 21

Views: 34376

Answers (1)

Gareth Latty
Gareth Latty

Reputation: 89097

zip() takes a variable number of arguments. zip(one, two, three) will work, and so on for as many arguments as you wish to pass in.

>>> for triple in zip([1, 2, 3], "abc", [True, False, None]):
...     print(triple)
... 
(1, 'a', True)
(2, 'b', False)
(3, 'c', None)

If you have an unknown number of iterables (a list of them, for example), you can use the unpacking operator (*) to unpack (use as arguments) an iterable of iterables:

>>> iterables = [[1, 2, 3], "abc", [True, False, None]]
>>> for triple in zip(*iterables):
...     print(triple)
... 
(1, 'a', True)
(2, 'b', False)
(3, 'c', None)

This is often referred to as unzipping as it will reverse the operation, e.g:

>>> iterables = ([1, 2, 3], 'abc', [True, False, None])
>>> iterables == next(zip(*zip(iterables)))
True

Upvotes: 45

Related Questions