在python中使用列表项索引作为另一个列表的索引

2024-09-29 22:33:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两份清单:

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

Tags: rmin列表fortrlistnodesset
2条回答

indices中循环并从removelistst中弹出指定的元素

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

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

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

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

相关问题 更多 >

    热门问题