python 维列表索引(嵌套列表)

x33g5p2x  于 2023-01-01  发布在  Python
关注(0)|答案(3)|浏览(181)

假设下面有一个列表,我如何在列表中找到已标识对象的所有索引
我的期望(所有指数的'笔'):

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)
zbq4xfa0

zbq4xfa01#

因为它被标记为numpy,下面是numpy的方法:

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)]
33qvvth1

33qvvth12#

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
ggazkfy8

ggazkfy83#

也许你可以先试试这个:
解释一下--因为它是一个嵌套列表,你需要先循环每个子列表,然后检查每个条目是否是 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)]

# You can even do this in one List Comprehension, if you'd like short code: 

ans = [(i, j) for i, ll in enumerate(lsts) for j, item in enumerate(ll) if item == 'pen']

相关问题