How do I take pairs from a list in python?

Let's say I have a list that looks like this:

['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9', 'item10']

Using Python, how would I grab pairs from it, where each element is paired with both elements before and after it?

['item1', 'item2']
['item2', 'item3']
['item3', 'item4']
['item4', 'item5']
['item5', 'item6']
['item6', 'item7']
['item7', 'item8']
['item8', 'item9']
['item9', 'item10']

It seems that I could hack something together, but I wonder if anyone has the elegant solution that they used before?

+3
source share
3 answers

A quick and easy way to do this would be something like:

a = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9', 'item10']

print zip(a, a[1:])

Which will produce the following:

[('item1', 'item2'), ('item2', 'item3'), ('item3', 'item4'), ('item4', 'item5'), ('item5', 'item6'), ('item6', 'item7'), ('item7', 'item8'), ('item8', 'item9'), ('item9', 'item10')]
+11
source

Check out the recipe pairwisein the itertoolsdocumentation .

+3
source

This should do the trick:

[(foo[i], foo[i+1]) for i in xrange(len(foo) - 1)]
+1
source

Source: https://habr.com/ru/post/1745342/


All Articles