Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through two lists with one of them shifted?

Tags:

python

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?

like image 879
Pangu Avatar asked Sep 11 '25 16:09

Pangu


2 Answers

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:

  • slice the second list to remove the tail: [:-1]
  • replace 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.

like image 78
mhlester Avatar answered Sep 14 '25 04:09

mhlester


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')]
like image 45
dawg Avatar answered Sep 14 '25 04:09

dawg