python - 从特定值之后的列表中删除所有元素

标签 python list indexing

给定一个列表 l1 = ['apple', 'pear', 'grapes, 'banana']

如何删除 'pear' 之后的所有项目

最佳答案

使用列表切片方法

>>> l1 = ['apple', 'pear', 'grapes', 'banana']
>>> target_ibdex = l1.index('pear')
>>> target_ibdex
1
>>> l1[:target_ibdex+1]
['apple', 'pear']
>>> 

当列表中不存在元素时进行异常处理。

>>> l1 = ['apple', 'pear', 'grapes', 'banana']
>>> target_element = "mango"
>>> try:
...     target_index = l1.index(target_element) + 1
... except ValueError, e:
...     target_index = None
... 
>>> l1[:target_index]
['apple', 'pear', 'grapes', 'banana']

当元素出现在列表中

>>> l1 = ['apple', 'pear', 'grapes', 'banana']
>>> target_element = "pear"
>>> try:
...     target_index = l1.index(target_element) + 1
... except ValueError, e:
...     target_index = None
... 
>>> l1[:target_index]
['apple', 'pear']

关于python - 从特定值之后的列表中删除所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28169671/

相关文章:

python - 两条线串的交集 Geopandas

python-3.x - 使用 pandas multiIndex 数据框进行选择

python - 与python列表: are they or are they not iterators?混淆

java - ArrayList每次显示的执行时间不同,为什么?

mysql - 索引对于大型数据库来说是好是坏?

python - Python也分LTS和稳定版吗?

python - 高级 Python 键盘事件?

python - 如何使用 xarray 查找网格数据的每日百分位数?

java - 为什么 Collections 实用程序类在 Java 中没有 Iterator 方法?

python ,排序