一个序列问题 [英] a sequence question
问题描述
1)我想迭代列表一次只有N
有点像:
#一次两个......不行,显然
对于a,b在[1,2,3,4]:
....打印a,b
....
回溯(大多数最近的电话最后一次):
文件"<互动输入>",第1行,在?
TypeError:unpack non-sequence
有没有一种很好的方法可以处理列表推导,
或者我只需要遍历列表吗?
欢呼和感谢
克里斯赖特
l = [1,2 ,3,4]
为a,b为zip(l [:: 2],l [1 :: 2]):
打印一个,b
-
问候,
Diez B. Roggisch
文章< lz ********** *********@news-server.bigpond.net.au> ;,
Chris Wright< wr ****** @ hotmail.com>写道:
1)我想迭代列表一次一个N
您可以使用切片和zip来实现:
l = [1,2, 3,4,5,6,7,8]
zip(l [:: 2],l [1 :: 2])
[(1,2),(3,4),(5,6),(7,8)]
对我来说,这有点神秘,但它确实有效,而且它肯定是紧凑的。我不会使用zip()或扩展切片;也许如果
我经常使用它们,如果我用其他人的代码阅读
,上面的内容会更明显。
有趣的是将其概括为N一次
的情况。我认为这样可行:
def nzip(list0,n):
args = []
for i in range( n):
slice = list0 [i :: n]
args.append(切片)
返回zip(* args)
l = [1,2,3,4,5,6,7,8,9,10,11,12]
print nzip(l,3 )
Roy-Smiths-Computer:play
./ nzip.py
[(1,2, 3),(4,5,6),(7,8,9),(10,11,12)]
但我没有考虑过什么如果
列表的长度不是n的倍数(读者的练习),则会发生。它也是令人讨厌的,因为上面会产生一堆临时列表。如果有一种方法让中间体成为发生器
表达式,那将会很酷。但是我对那些东西不是很好,所以我会留下
作为其他读者的练习:-)
Hi,
1) I want to iterate over a list "N at a time"
sort of like:
# Two at a time... won''t work, obviously
for a, b in [1,2,3,4]: .... print a,b
....
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: unpack non-sequence
Is there a nifty way to do with with list comprehensions,
or do I just have to loop over the list ?
cheers and thanks
chris wright
l = [1,2,3,4]
for a, b in zip(l[::2], l[1::2]):
print a,b
--
Regards,
Diez B. Roggisch
In article <lz*******************@news-server.bigpond.net.au>,
Chris Wright <wr******@hotmail.com> wrote:
Hi,
1) I want to iterate over a list "N at a time"
You could do it with slicing and zip:
l = [1, 2, 3, 4, 5, 6, 7, 8]
zip (l[::2], l[1::2])
[(1, 2), (3, 4), (5, 6), (7, 8)]
To my eyes, that''s a bit cryptic, but it works and it''s certainly
compact. I don''t use either zip() or extended slicing a lot; perhaps if
I used them more often, the above would be more obvious to me if I read
it in somebody else''s code.
The interesting thing would be generalizing this to the "N at a time"
case. I think this works:
def nzip (list0, n):
args = []
for i in range(n):
slice = list0[i::n]
args.append (slice)
return zip (*args)
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
print nzip (l, 3)
Roy-Smiths-Computer:play
./nzip.py
[(1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, 12)]
but I haven''t given any thought to what happens if the length of the
list isn''t a multiple of n (exercise for the reader). It''s also
annoying that the above generates a bunch of temporary lists. It would
be cool if there was a way to have the intermediates be generator
expressions, but I''m not that good with that stuff, so I''ll leave that
as an exercise for other readers :-)
这篇关于一个序列问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!