【问题标题】:Use list item index as index to another list in python使用列表项索引作为python中另一个列表的索引
【发布时间】:2020-11-23 16:03:47
【问题描述】:

我有两个列表:

A = ['PA', 'AT', 'TR']
removlistv = ['TR', 'AI', 'IO', 'SO', 'CR', 'PH', 'RT']

我找到了两个列表的交集:

rm_nodes = set(A) & set(removelistv)

创建集合{'TR'}。我现在想在removelistv 列表中找到那个(或多个)交叉点的索引:

indices = [removelistv.index(x) for x in rm_nodes]

到目前为止一切顺利,indices 包含正确的值。 当我想使用索引值(在本例中为[0] 即列表)检索第三个列表removelistst = ['TR0', 'AI1', 'IO1', 'SO0', 'CR1', 'PH0', 'RT1'] 中的匹配项时,问题就开始了。我的目标是从removelistst 中删除项目'TR0'。基本上,我想根据开始时两个列表的交集的输出从这个列表中删除项目。

我尝试了以下方法:

numbers =[ int(x) for x in indices ]
removelistst[numbers]

返回错误:

TypeError: list indices must be integers or slices, not list

【问题讨论】:

  • 请用您尝试过的代码更新您的问题。
  • removelistst 中的元素是否不同?
  • 你就不能removelistst.remove(value + str(index))吗?
  • @quamrana 我刚刚做了,谢谢
  • @Barmar 是的,他们是

标签: python list indexing


【解决方案1】:

遍历indices并将指定元素弹出removelistst。

for index in sorted(indices, reverse=True):
    removelistst.pop(index)

我将indices 反向排序,这样删除一个元素不会影响后面要删除的元素的索引。

【讨论】:

  • 谢谢,我试了一下不排序观察问题。
【解决方案2】:

有很多方法可以做到这一点,这里有一个列表理解:

removelistst = [value for index, value in enumerate(removelistst) if index not in numbers]

【讨论】:

    猜你喜欢
    • 2016-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 2018-04-02
    • 2010-11-03
    • 1970-01-01
    相关资源
    最近更新 更多