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.
例如,对于未知长度的序列,获取最后 n 个元素的最“Pythonic”方式是什么?
显然我可以计算开始和结束索引。有什么更光滑的吗?
是的,通过使用负索引:
last_five = somesequence[-5:]
切片中的负索引与序列长度相关。
使用负索引。
seq[-1]是序列的最后一个元素。seq[-3:]给你最后三个。
seq[-1]
seq[-3:]
尝试:
sequence[-n:]
(让 Stack Overflow 开心的文字)