Reputation: 151
I found an interesting function in Julia called zip
. zip orders the calls to its subiterators in such a way that stateful iterators will not advance when another iterator finishes in the current iteration.
I would like to create a similar kind of code that gives output similar to Julia's zip
.
For example, say a=1:5
and b=["e","d","b","c","a"]
, I would like to have an output where each value of both datasets is selected like this:
(1,"e"),(2,"d"), (3,"b")
and so on.
Is there any possible way to do this in Python?
Upvotes: 0
Views: 71
Reputation: 757
This is done by the zip() function in Pyhton.
Here is some documentation about it. The description says :
Returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.
The returned list is truncated in length to the length of the shortest argument sequence. When there are multiple arguments which are all of the same length, zip() is similar to map() with an initial argument of None. With a single sequence argument, it returns a list of 1-tuples. With no arguments, it returns an empty list.
The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n).
And here are a few examples :
zip('foo', 'bar')
>>> [('f', 'b'), ('o', 'a'), ('o', 'r')]
zip((1, 1), (2, 4))
>>> [(1, 2), (1, 4)]
zip((1, 2, 3), (4, 5))
>>> [(1, 4), (2, 5)]
zip(range(1,6), ['a','b','c','f','k'])
>>> [(1,'a'), (2,'b'), (3,'c'), (4,'f'), (5,'k')]
Upvotes: 1