gpt4 book ai didi

python - 如何使用 3 个冒号分隔符反向显示列表?

转载 作者:行者123 更新时间:2023-12-03 21:13:40 25 4
gpt4 key购买 nike

如何让第三行与第二行做同样的事情?

list = [1,2,3,4,5,6,7,8,9,10]
print(list[::-1])
print(list[-1:0:-1])

这是我得到的结果:
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
[10, 9, 8, 7, 6, 5, 4, 3, 2]

最佳答案

你应该在这里省略 0:

print(list[-1:0:-1])

并将其写为
print(list[-1::-1])

或地点 None :
print(list[-1:None:-1])

原因是:当您在“3 个冒号分隔符”中省略停止值(或替换 None )时, this会发生:

If i or j are omitted or None, they become “end” values (which end depends on the sign of k).



哪里 j这里对应于停止值(并且 i 是开始,即 [i:j:k] )

关于python - 如何使用 3 个冒号分隔符反向显示列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61992788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com