Python拼接列表在向后工作时不包括第一个元素

问题描述 投票:0回答:1
new_list = [i + 1 for i in range(16)]

sec_list = new_list[(len(new_list) - 2):0:-2]

print(new_list)

print(sec_list)

实际输出

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

[15, 13, 11, 9, 7, 5, 3]

所需的输出:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

[15, 13, 11, 9, 7, 5, 3, 1] <---- I want the 1 to be present

只是想弄清楚它是如何工作的。我以为[开始:结束:增加/减少]

python list splice
1个回答
0
投票

这是您需要的

sec_list = new_list[(len(new_list) - 2)::-2]
print(sec_list) # [15, 13, 11, 9, 7, 5, 3, 1]
© www.soinside.com 2019 - 2024. All rights reserved.