python list 迭代_在Python中迭代列表(循环方式)中的对

作者分享了两种Python非标准方法来遍历列表并生成配对,包括使用`zip`和切片,同时寻求更Pythonic的解决方案,并展示了自定义函数`ntuples`处理不同情况。讨论了可能存在的预定义函数和通用n元组版本。
摘要由CSDN通过智能技术生成

The problem is easy, I want to iterate over each element of the list and the next one in pairs (wrapping the last one with the first).

I've thought about two unpythonic ways of doing it:

def pairs(lst):

n = len(lst)

for i in range(n):

yield lst[i],lst[(i+1)%n]

and:

def pairs(lst):

return zip(lst,lst[1:]+[lst[:1]])

expected output:

>>> for i in pairs(range(10)):

print i

(0, 1)

(1, 2)

(2, 3)

(3, 4)

(4, 5)

(5, 6)

(6, 7)

(7, 8)

(8, 9)

(9, 0)

>>>

any suggestions about a more pythonic way of doing this? maybe there is a predefined function out there I haven't heard about?

also a more general n-fold (with triplets, quartets, etc. instead of pairs) version could be interesting.

解决方案

I've coded myself the tuple general versions, I like the first one for it's ellegant simplicity, the more I look at it, the more Pythonic it feels to me... after all, what is more Pythonic than a one liner with zip, asterisk argument expansion, list comprehensions, list slicing, list concatenation and "range"?

def ntuples(lst, n):

return zip(*[lst[i:]+lst[:i] for i in range(n)])

The itertools version should be efficient enough even for large lists...

from itertools import *

def ntuples(lst, n):

return izip(*[chain(islice(lst,i,None), islice(lst,None,i)) for i in range(n)])

And a version for non-indexable sequences:

from itertools import *

def ntuples(seq, n):

iseq = iter(seq)

curr = head = tuple(islice(iseq, n))

for x in chain(iseq, head):

yield curr

curr = curr[1:] + (x,)

Anyway, thanks everybody for your suggestions! :-)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值