【问题标题】:python delete multiple items from list by index, including negative indexpython按索引从列表中删除多个项目,包括负索引
【发布时间】:2015-08-29 20:51:44
【问题描述】:

我知道按索引从列表中删除多个不相邻的元素已经介绍过了,但是如果索引为负数怎么办?例如,list[len(list) - 1] 和 list[-1] 都指向同一个元素,但它们在存储时是不同的数字,如果我们尝试“先删除较大的索引”策略,它们的排序方式也会不同。

【问题讨论】:

  • 您能否添加一些代码来解释您的意思?列表元素怎么可能有负索引?第一个元素由[0] 索引,最后一个元素由[-1] 索引,等于[len(l)-1]。
  • @albert Python 列表中没有-1 索引,这就是它在获取值时应用的所有逻辑,请在下面查看我的答案。
  • 如果所有指数都是负数,则策略相同,您只需反转逻辑即可。如果混合了正面和负面,则需要先将它们归一化。
  • 我问的原因是因为我试图避免处理 len(list) 因为我实际上只处理列表的开头和结尾部分,即 i = 1, 2 , 3, -2, -1。这些值存储为“键”以记住元素的位置,如果我想稍后删除它们
  • 如果你确定不会有歧义,你可以在你的逻辑中使用正数和负数。将负值视为大于正值。

标签: python list


【解决方案1】:

Python Lists 中没有负索引,当您尝试使用负索引时,Python 中会发生这种情况...

if (index < 0) {
    index  = index + len(list) # this is just a pseudo code
}

Python 通过使用index 应用逻辑来获取值。

>>> l = [0, 1, 2, 3, 4]
>>> l[-1]
4
>>> l[-2]
3

这里它应用得很好,因为我们刚刚尝试了-1 and -2,如果你超出了列表中的len,例如,上面的列表长度是5,假设如果你尝试l[-6],它会尝试应用上面的逻辑并检查此5 + (-6) ==&gt; -1,但该值仍为负数,并且列表中没有-1 的索引,这将引发IndexError 异常,如下所示。

>>> l[-6]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range 

顺便说一句这是 Python 适用于 list insert..

的逻辑
if (where < 0) {
    where += n;
    if (where < 0) # here "where" is index that we trying to insert
        where = 0; # "n" is length of the list
}
if (where > n)
    where = n;

这里的where 是index 值尝试insert into list。 n 是列表的长度。

您可以通过以下链接了解有关列表的更多信息..

http://gsb-eng.com/pythonlistinternals/

【讨论】:

    猜你喜欢
    • 2016-04-22
    • 2019-01-16
    • 2018-11-04
    • 2023-04-05
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    • 2020-11-09
    • 1970-01-01
    相关资源
    最近更新 更多