[英]Most pythonic (and efficient) way of nesting a list in pairs
my list is: 我的清单是:
mylist=[1,2,3,4,5,6]
I would like to convert mylist into a list of pairs: 我想将mylist转换为对列表:
[[1,2],[3,4],[5,6]]
Is there a pythonic way of doing so? 有这样做的pythonic方式吗? List comprehension? 列表理解? Itertools? Itertools?
Yeppers, list comprehension is my usual way of doing it: Yeppers,list comprehension是我通常的做法:
>>> groupsize = 2
>>> [mylist[x:x+groupsize] for x in range(0,len(mylist),groupsize)]
[[1,2],[3,4],[5,6]]
>>> groupsize = 3
>>> [mylist[x:x+groupsize] for x in range(0,len(mylist),groupsize)]
[[1,2,3],[4,5,6]]
I use range
for portability, if you are using python 2 (you probably are) change the range
to xrange
to save memory. 我使用range
来实现可移植性,如果你使用python 2(你可能是)将range
更改为xrange
以节省内存。
My preferred technique: 我的首选技术:
>>> mylist = [1, 2, 3, 4, 5, 6]
>>> mylist = iter(mylist)
>>> zip(mylist, mylist)
[(1, 2), (3, 4), (5, 6)]
I usually use generators instead of lists anyway, so line 2 usually isn't required. 我通常使用生成器代替列表,因此通常不需要第2行。
An alternate way: 另一种方式:
zip( mylist[:-1:2], mylist[1::2] )
Which produces a list of tuples: 这会产生一个元组列表:
>>> zip(mylist[:-1:2],mylist[1::2])
[(1, 2), (3, 4), (5, 6)]
If you really want a list of lists: 如果你真的想要一个列表列表:
map(list, zip(mylist[:-1:2],mylist[1::2]))
Check out the "grouper" recipe from the itertools documentation : 查看itertools文档中的“grouper”配方:
def grouper(n, iterable, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
[mylist[2*n:2*n+2] for n in xrange(len(mylist)/2)]
This solution combines the use of list comprehensions and slicing to extract pairs in sequence from the original list, and build a list of the slices. 此解决方案结合使用列表推导和切片从原始列表中依次提取对,并构建切片列表。
Alternatively, [mylist[n:n+2] for n in xrange(0, len(mylist), 2)]
which is the same except xrange
counts by twos instead of the slices. 或者, [mylist[n:n+2] for n in xrange(0, len(mylist), 2)]
除了xrange
之外是相同的,而不是切片。 Thanks to Steven Rumbalski for the suggestion. 感谢Steven Rumbalski提出的建议。
And now for something completely different: here is a solution (ab)using zip
and an ephemeral function instead of intermediate assignment: 现在有一些完全不同的东西:这是一个使用zip
和短暂函数而不是中间赋值的解决方案(ab):
>>> (lambda i: zip(i, i))(iter(mylist))
[(1, 2), (3, 4), (5, 6)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.