开发者

How should I grab pairs from a list in python?

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 item is included in a pair with both the item before and after it?

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

Seems like someth开发者_开发问答ing i could hack together, but I'm wondering if someone has an elegant solution they've used before?


A quick and simple way of doing it 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')]


Check out the pairwise recipe in the itertools documentation.


This should do the trick:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜