TransWikia.com

Use list item index as index to another list in python

Stack Overflow Asked by jonna_983 on February 7, 2021

I have two lists:

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

I find the intersection of the two lists:

rm_nodes = set(A) & set(removelistv)

Which creates the set {'TR'}. I now want to find the index of that intersection (or intersections) in the list removelistv:

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

So far so good, indices contains the correct value.
The problem starts when I want to use the index value (which in this case is [0] i.e. a list) to retrieve the matching item in a third list removelistst = ['TR0', 'AI1', 'IO1', 'SO0', 'CR1', 'PH0', 'RT1']. My goal is to remove the item 'TR0' from removelistst. Basically, I want to remove items from this list based on the output of the intersection of the two lists in the beginning.

I’ve tried the following:

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

Which returns the error:

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

2 Answers

There's lots of ways to do this, here's a list comprehension:

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

Answered by Bill Lynch on February 7, 2021

Loop through indices and pop the specified element out of removelistst.

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

I sort indices in reverse so that removing an element won't affect the indexes of later elements to be removed.

Answered by Barmar on February 7, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP