迭代器问题 [英] iterator question
问题描述
任何改变序列的建议:
[1,2,3,4 ...]
其中1,2,3 ..它是一个任意序列中的第i个项目
成为一系列元组:
[(1,2),(3,4) )...]
换句话说,给定一个seq和一个整数来指定要返回的元组
的大小,那么例如:
seq = [a,b,c,d,e,f]
变换中的e(seq,2):
打印e
将返回
(a,b)
(c,d)
(e,f)
Any suggestions for transforming the sequence:
[1, 2, 3, 4...]
Where 1,2,3.. are it the ith item in an arbitrary sequence
into a succession of tuples:
[(1, 2), (3, 4)...]
In other words, given a seq and an integer that specifies the size of tuple
to return, then for example:
seq = [a,b,c,d,e,f]
for e in transform (seq, 2):
print e
would return
(a,b)
(c,d)
(e,f)
推荐答案
def transform(seq,size):
i = 0
而我< len(seq):
收益元组(seq [i:i + size])
i + = size
Neal Becker写道:
def transform(seq, size):
i = 0
while i < len(seq):
yield tuple(seq[i:i+size])
i += size
Neal Becker wrote:
任何改变序列的建议:
[1,2,3,4 ...]
其中1,2,3 ..是一个任意序列中的第i个项目
成为一系列元组:
[(1,2),(3,4)...]
换句话说,给定一个seq和一个指定元组大小的整数/>
返回,然后例如:
seq = [a,b,c,d,e,f]
for e在变换(seq,2):
打印e
将返回
(a,b)
(c,d)
(e,f)
Any suggestions for transforming the sequence:
[1, 2, 3, 4...]
Where 1,2,3.. are it the ith item in an arbitrary sequence
into a succession of tuples:
[(1, 2), (3, 4)...]
In other words, given a seq and an integer that specifies the size of tuple
to return, then for example:
seq = [a,b,c,d,e,f]
for e in transform (seq, 2):
print e
would return
(a,b)
(c,d)
(e,f)
Neal Becker写道:
Neal Becker wrote:
任何改变序列的建议:
[1,2,3,4 ...]
其中1,2,3 ..是任意序列中的第i项
into一连串的元组:
[(1,2),(3,4)......]
换句话说,给定一个seq和一个整数,指定要返回的元组大小
,然后例如:
seq = [a,b,c,d,e ,f]
for e in transform(seq,2):
print e
将返回
(a,b)
(c,d)
(e,f)
Any suggestions for transforming the sequence:
[1, 2, 3, 4...]
Where 1,2,3.. are it the ith item in an arbitrary sequence
into a succession of tuples:
[(1, 2), (3, 4)...]
In other words, given a seq and an integer that specifies the size of tuple
to return, then for example:
seq = [a,b,c,d,e,f]
for e in transform (seq, 2):
print e
would return
(a,b)
(c,d)
(e,f)
怎么样:
def转换(seq,n):
$ x $ b for x in xrange(0,len(seq),n):
产生元组(seq [k:k + n])
How about this:
def transform(seq,n):
for k in xrange(0,len(seq),n):
yield tuple(seq[k:k+n])
jo ******** @ gmail.com 写道:
jo********@gmail.com wrote:
def transform(seq,size) :
i = 0
而i< len(seq):
收益元组(seq [i:i + size])
i + = size
def transform(seq, size):
i = 0
while i < len(seq):
yield tuple(seq[i:i+size])
i += size
或任意迭代,而不仅仅是序列:
来自itertools import islice
def transform(可迭代,大小):
it = iter(iterable)
而True:
window = tuple(islice(it,size))
如果不是窗口:
休息
收益窗口
乔治
Or for arbitrary iterables, not just sequences:
from itertools import islice
def transform(iterable, size):
it = iter(iterable)
while True:
window = tuple(islice(it,size))
if not window:
break
yield window
George
这篇关于迭代器问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!