My question is how do you start one list at the next index when iterating?
for elem1, elem2 in zip(unigram_mixture_list, bigram_mixture_list):
print elem1, elem2
I want to start looping through elem1
one index ahead.
How would I achieve this in python?
slice the first list with [1:]
:
for elem1, elem2 in zip(unigram_mixture_list[1:], bigram_mixture_list):
You got everything else exactly right
Note that if the lists were the same length, but now truncated because you've shortened one, you have a couple choices:
[:-1]
zip
with itertools.izip_longest
(after import itertools
)Example with izip_longest
:
import itertools
# ~~~ other code ~~~ #
for elem1, elem2 in itertools.izip_longest(unigram_mixture_list[1:], bigram_mixture_list):
print elem1, elem2
Edit: In python 3, izip_longest
was renamed zip_longest
, so use that instead.
There is the zip
approach, but if the lists are the same length the longer will be truncated:
>>> li1='abcdefg'
>>> li2='1234567'
>>> zip(li1[1:], li2)
[('b', '1'), ('c', '2'), ('d', '3'), ('e', '4'), ('f', '5'), ('g', '6')]
# NOTE -- '7' is dropped from li2...
With Python 2, you can use map
:
>>> map(None, li1[1:], li2)
[('b', '1'), ('c', '2'), ('d', '3'), ('e', '4'), ('f', '5'), ('g', '6'), (None, '7')]
# NOTE -- We ran out of li1, so start using 'None'
For both Python 2 and 3, you can use izip_longest from itertools:
>>> from itertools import izip_longest
>>> list(izip_longest(li1[1:], li2))
[('b', '1'), ('c', '2'), ('d', '3'), ('e', '4'), ('f', '5'), ('g', '6'), (None, '7')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With