假设我有一个包含X元素的列表
[4,76,2,8,6,4,3,7,2,1...]
Run Code Online (Sandbox Code Playgroud)
我想要前5个元素.除非它少于5个元素.
[4,76,2,8,6]
Run Code Online (Sandbox Code Playgroud)
怎么做?
Mar*_*off 75
你只需用它来[:5]表示你想要(最多)前5个元素.
>>> [1,2,3,4,5,6,7,8][:5]
[1, 2, 3, 4, 5]
>>> [1,2,3][:5]
[1, 2, 3]
>>> x = [6,7,8,9,10,11,12]
>>> x[:5]
[6, 7, 8, 9, 10]
Run Code Online (Sandbox Code Playgroud)
此外,将冒号放在数字的右侧意味着从第n个元素开始计数 - 不要忘记列表是从0开始的!
>>> x[5:]
[11, 12]
Run Code Online (Sandbox Code Playgroud)
war*_*iuc 29
要在不创建副本的情况下修剪列表,请使用del:
>>> t = [1, 2, 3, 4, 5]
>>> # delete elements starting from index 4 to the end
>>> del t[4:]
>>> t
[1, 2, 3, 4]
>>> # delete elements starting from index 5 to the end
>>> # but the list has only 4 elements -- no error
>>> del t[5:]
>>> t
[1, 2, 3, 4]
>>>
Run Code Online (Sandbox Code Playgroud)