从序列中生成元组 [英] generate tuples from sequence
问题描述
我想要一个生成器,它接受序列并产生包含
n项目的元组,但是忽略了''奇怪的''项目。例如
take_group(范围(9),3) - (0,1,2)(3,4,5)(6,7,8)
这就是我想出的......
def take_group(gen,count):
i = iter(gen)
而True:
产生元组([i.next()for _ in xrange(count)])
这是最有效的解决方案?
问候,
将McGugan
-
http://www.willmcgugan.com
Will McGugan写道:
我想要一个生成器,它接受一个序列并产生包含sqeuence的
n项目的元组,但是忽略了''odd''项。例如
忘记添加,为了我的目的,我将总是有一个序列,其中n个项目的数量为
。
将
请问McGugan写道:
我想要一个生成器接受序列并产生包含sqeuence的
n项的元组,但忽略''odd''项。例如
take_group(范围(9),3) - (0,1,2)(3,4,5)(6,7,8)
我喜欢
>> items =范围(9)
N = 3
zip(* [iter(items)] * N)
[(0,1,2),(3,4,5),(6,7,8)]
Peter
2007年1月17日04:50:33 -0800,Will McGugan< wi ** @ willmcgugan.comwrote:
>
Will McGugan写道:
我想要一个带序列的发电机并且产生包含sqeuence的
n项的元组,但忽略''odd''项。例如
忘记添加,为了我的目的,我总是会有一个序列,其中n个项目的数量为
。
类似.......
>> [(x,x + 1,x + 2)for x in xrange(0,9,3)]
[(0,1,2),(3,4,5),(6,7,8)]
HTH:)
Hi,
I''d like a generator that takes a sequence and yields tuples containing
n items of the sqeuence, but ignoring the ''odd'' items. For example
take_group(range(9), 3) -(0,1,2) (3,4,5) (6,7,8)
This is what I came up with..
def take_group(gen, count):
i=iter(gen)
while True:
yield tuple([i.next() for _ in xrange(count)])
Is this the most efficient solution?
Regards,
Will McGugan
--
http://www.willmcgugan.com
Will McGugan wrote:
Hi,
I''d like a generator that takes a sequence and yields tuples containing
n items of the sqeuence, but ignoring the ''odd'' items. For exampleForgot to add, for my purposes I will always have a sequence with a
multiple of n items.
Will
Will McGugan wrote:
I''d like a generator that takes a sequence and yields tuples containing
n items of the sqeuence, but ignoring the ''odd'' items. For example
take_group(range(9), 3) -(0,1,2) (3,4,5) (6,7,8)I like
>>items = range(9)
N = 3
zip(*[iter(items)]*N)
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]
Peter
On 17 Jan 2007 04:50:33 -0800, Will McGugan <wi**@willmcgugan.comwrote:>
Will McGugan wrote:
Hi,
I''d like a generator that takes a sequence and yields tuples containing
n items of the sqeuence, but ignoring the ''odd'' items. For example
Forgot to add, for my purposes I will always have a sequence with a
multiple of n items.something along the lines of.......
>>[ (x,x+1,x+2) for x in xrange(0,9,3) ]
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]
HTH :)
这篇关于从序列中生成元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!