如何在Python中修剪列表 [英] How to trim a list in Python

查看:76
本文介绍了如何在Python中修剪列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含X个元素的列表

Suppose I have a list with X elements

[4,76,2,8,6,4,3,7,2,1...]

我想要前5个元素.除非元素少于5个.

I'd like the first 5 elements. Unless it has less than 5 elements.

[4,76,2,8,6]

该怎么做?

推荐答案

您只需用[:5]对其进行子索引化,即可表示您希望(最多)前5个元素.

You just subindex it with [:5] indicating that you want (up to) the first 5 elements.

>>> [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的!

Also, putting the colon on the right of the number means count from the nth element onwards -- don't forget that lists are 0-based!

>>> x[5:]
[11, 12]

这篇关于如何在Python中修剪列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆