假设我有一个包含X元素的列表
[4,76,2,8,6,4,3,7,2,1...]
我想要前5个元素。除非它少于5个元素。
[4,76,2,8,6]
怎么做?
答案 0 :(得分:73)
您只需使用[: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]
此外,将冒号放在数字右侧意味着从第n个元素开始计数 - 不要忘记列表是从0开始的!
>>> x[5:]
[11, 12]
答案 1 :(得分:24)
要修改列表而不创建副本,请使用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]
>>>
答案 2 :(得分:1)
>>> [1,2,3,4,5,6,7,8,9][:5]
[1, 2, 3, 4, 5]
>>> [1,2,3][:5]
[1, 2, 3]
答案 3 :(得分:0)
l = [4,76,2,8,6,4,3,7,2,1]
l = l[:5]