Home > other >  index for dimensional list (nested list)
index for dimensional list (nested list)

Time:12-31

Assuming I have a list below, how can I find all the indexes of an identified object in the list

WHAT I AM EXPECTING (ALL indexes of 'pen'):

OUTPUT: (0,0),(3,4),(4,4),(4,2),(3,4)
a_list = [['pen', 'pencil', 'eraser'], 
          ['ruler', 'paper', 'pen'], 
          ['pen', 'pen', 'bag'], 
          ['pencil', 'pen', 'paper']]


def finding(listoflist, stationary):
    for i in listoflist:
        if stationary in i:
            return (i.index(stationary)),(listoflist.index(i))

finding(a_list, 'pen')

OUTPUT: (0, 0)

CodePudding user response:

Since it was tagged numpy, here is the numpy approach:

import numpy as np

stationary = np.array([
    ['pen', 'pencil', 'eraser'], 
    ['ruler', 'paper', 'pen'], 
    ['pen', 'pen', 'bag'], 
    ['pencil', 'pen', 'paper']
])

out = list(zip(*np.where(stationary == "pen")))
[(0, 0), (1, 2), (2, 0), (2, 1), (3, 1)]

CodePudding user response:

Maybe you can try this first:

Explain - since it's a nested lists, you need to loop each sub-list first, then go through each item to check if it's the stationary.


a_list = [['pen', 'pencil', 'eraser'], 
          ['ruler', 'paper', 'pen'], 
          ['pen', 'pen', 'bag'], 
          ['pencil', 'pen', 'paper']]


def finding(lsts, stationary):
    result = []
    
    for i, ll in enumerate(lsts):
        for j, item in enumerate(ll):
            if item == stationary:
                result.append((i, j))
    return result

print(finding(a_list, 'pen'))
# [(0, 0), (1, 2), (2, 0), (2, 1), (3, 1)]

CodePudding user response:

def fun(a_list,search_item):
    res=[]
    for i1,nest in enumerate(a_list):
        for i2,item in enumerate(a_list[i1]):
            if item==search_item:
                res.append((i1,i2))
    return res
  • Related