【问题标题】:How can i delete elements in a list with remove order? [duplicate]如何使用删除顺序删除列表中的元素? [复制]
【发布时间】:2020-07-24 13:47:15
【问题描述】:

我有一个像 lst = [1,3,5] 这样的列表和一个像 lost =['the' , 'cat' , 'thinks' , 'you' , 'are' , 'crazy' ] 这样的主要列表

我想根据第一个列表中的索引删除第二个列表中的元素。这意味着我必须删除 'cat' 、 'you' 和 'crazy' 。

问题是如果我使用:

lost.remove(lost[1])
lost.remove(lost[3])
lost.remove(lost[5])

第一个问题是它不会成功! 因为当我们删除第一个元素时,列表的长度(named lost)会减少 这样我们就会删除错误的元素。

第二个问题是名为(lst) 的列表并不总是 [1,3,5] 。会变长 在元素中。

我该如何解决这个问题?

【问题讨论】:

  • 删除降序索引顺序的元素:5,3,1

标签: python python-3.x list maxlength


【解决方案1】:

作为@np8commented,您可以按降序索引顺序删除元素,如下所示:

lst = [1, 3, 5]
lost = ['the', 'cat', 'thinks', 'you', 'are', 'crazy']

for index in reversed(lst):  # descending index order
    del lost[index]

print(lost)

打印出来的

['the', 'thinks', 'are']

更新(感谢@wwiithe comment

如果给定的lst 未按升序排序,则可以改为:

lst = [3, 1, 5]
lost = ['the', 'cat', 'thinks', 'you', 'are', 'crazy']

for index in sorted(lst, reverse=True):  # descending index order
    del lost[index]

【讨论】:

  • 如果lst = [3,1,5]怎么办?
  • @wwii 哈哈,我什至没有想到!谢谢你的评论!然后,可以使用for index in sorted(lst, reverse=True): del lost[index] 代替。
  • @wwii 我更新了我的帖子。再次感谢!
【解决方案2】:

您创建的不是带有{} 的列表,而是一个集合。如果要创建列表,则需要使用 [] 字符。之后,您可以像这样从列表中删除元素:

indexes = {1,3,5}
lst = ['the' , 'cat' , 'thinks' , 'you' , 'are' , 'crazy']

lst_dct = dict(enumerate(lst))
for index in indexes:
    lst_dct.pop(index)

new_lst = list(lst_dct.values())

new_lst 现在将包含其余元素。

除了需要元素的remove 函数,您还需要使用pop 根据索引从列表中删除元素。

【讨论】:

  • 您的解决方案与 OP 试图解决的问题相同。
  • @wwii 你说得对,我相应地改变了答案
【解决方案3】:

每次从列表中删除一个元素,比如说根据lost[i],从i遍历lost到最后,所有值减1。

【讨论】:

  • 我将如何用 python 做到这一点?
【解决方案4】:

您可以使用list comprehension 解决它,如下所示:

lst = [1,3,5]
lost =['the' , 'cat' , 'thinks' , 'you' , 'are' , 'crazy' ]

print([ val for idx, val in enumerate(lost) if idx not in lst])

应该是:['the', 'thinks', 'are']希望对你有帮助

【讨论】:

  • 您的解决方案是否特别有效,因为它是一个列表理解或 for 循环可以工作?它是否有效,因为它创建了一个新列表而不是从原始列表中删除项目?
  • 它也可以与for loop 一起使用,但您可以用单行代码解决它。主要原因是当你想按索引删除项目时,你会遇到麻烦,因为长度列表每次都会改变
【解决方案5】:

您也可以使用带有条件的列表推导。

lst = [1,3,5]
lost =['the' , 'cat' , 'thinks' , 'you' , 'are' , 'crazy' ]
copy_list=[lost[i] for i in range(len(lost)) if not i in lst]

【讨论】:

  • 你能用 for 循环来做,还是因为它是一个列表理解而专门工作?
  • @wwii 它也可以用于循环,只是写起来会更长!底层的列表推导实现了循环并使代码可读。
【解决方案6】:

如果空间不是问题,你可以使用这个:

import numpy as np

lst = [1, 3, 5]
lost =['the' , 'cat' , 'thinks' , 'you' , 'are' , 'crazy' ]
output = np.delete(lost, lst).tolist()
print(output)

输出:

['the', 'thinks', 'are']

【讨论】:

    【解决方案7】:

    循环索引 添加不需要的部分

    
    new = [lost[i] for i in range(len(lost)) if i not in lst]
       
    
    
    
    

    【讨论】:

    • 更好:像这样使用enumeratenew = [word for index, word in enumerate(lost) if index not in lst]。如果lst 很大,您可能想先从中创建一个set 以加快速度。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-05
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-11
    相关资源
    最近更新 更多