从交替的边循环列表 [英] Cycle a list from alternating sides

查看:98
本文介绍了从交替的边循环列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个清单

a = [0,1,2,3,4,5,6,7,8,9]

我怎样才能获得

b = [0,9,1,8,2,7,3,6,4,5]

也就是说,产生一个新的列表,其中每个连续的元素交替地从原始列表的两边取出?

That is, produce a new list in which each successive element is alternately taken from the two sides of the original list?

推荐答案

>>> [a[-i//2] if i % 2 else a[i//2] for i in range(len(a))]
[0, 9, 1, 8, 2, 7, 3, 6, 4, 5]

说明:

此代码从头开始选择数字( a [i // 2] )并从最后选择( a [-i // 2] a ,交替地(,如果i%2其他)。选择总计 len(a)的数字,因此即使 len(a),也不会产生任何不良影响奇数。

[ - i // 2 for i in range(len(a))] yield 0,-1 ,-1,-2,-2,-3,-3,-4,-4,-5

[i // 2 for i in range(len(a))] yield 0,0,1,1,2,2,3,3,4,4

i%2 False 之间交替显示True

所以我们从 a 中提取的索引是: 0,-1,1, -2,2,3,3,4,4,5

Explanation:
This code picks numbers from the beginning (a[i//2]) and from the end (a[-i//2]) of a, alternatingly (if i%2 else). A total of len(a) numbers are picked, so this produces no ill effects even if len(a) is odd.
[-i//2 for i in range(len(a))] yields 0, -1, -1, -2, -2, -3, -3, -4, -4, -5,
[ i//2 for i in range(len(a))] yields 0, 0, 1, 1, 2, 2, 3, 3, 4, 4,
and i%2 alternates between False and True,
so the indices we extract from a are: 0, -1, 1, -2, 2, -3, 3, -4, 4, -5.

我对pythonicness的评估:

关于这个单线程的好处是它很短并且显示对称性( + i // 2 -i // 2 )。

但不好的是,这种对称性具有欺骗性:

认为 -i // 2 i // 2 相同,并且标志被翻转。 但在Python中,整数除法返回发言权而不是截断为零。所以 -1 // 2 == -1

另外,我发现通过索引访问列表元素比pythonic更少迭代。

My assessment of pythonicness:
The nice thing about this one-liner is that it's short and shows symmetry (+i//2 and -i//2).
The bad thing, though, is that this symmetry is deceptive:
One might think that -i//2 were the same as i//2 with the sign flipped. But in Python, integer division returns the floor of the result instead of truncating towards zero. So -1//2 == -1.
Also, I find accessing list elements by index less pythonic than iteration.

这篇关于从交替的边循环列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆