Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
将列表拆分为由的偶数索引元素和的奇数索引元素组成的最Pythonic的方法是什么?ABCBACA
A
B
C
例如A = [1, 3, 2, 6, 5, 7]。那么B应该是[1, 2, 5],C应该是[3, 6, 7]。
A = [1, 3, 2, 6, 5, 7]
[1, 2, 5]
[3, 6, 7]
使用步幅切片:
B, C = A[::2], A[1::2]
序列切片不仅支持指定开始值和结束值,还支持步幅(或步长);[::2]选择从 0 开始的第二个值,[1::2]每个值从 1 开始。
[::2]
[1::2]
演示:
>>> A = [1, 3, 2, 6, 5, 7] >>> B, C = A[::2], A[1::2] >>> B [1, 2, 5] >>> C [3, 6, 7]