如何确定子列表中元素的索引

4
如何知道嵌套列表中元素的索引?这里有一个关于没有嵌套的列表的类似问题。
例如:
L=[[1, 2, 3], [4, 5, 6]]

当元素为3时,我期望的输出结果是:
output=[0][2]

你能举个例子吗? - user1781434
你可以用和那个链接中相同的方法来完成它。 - MooingRawr
请告诉我们您所说的 output = [0][2] 的含义,因为这肯定会引发异常。 - user1781434
6个回答

3

试试这个:

def get_sublist_index(lists, item):
    for sublist in lists:
        if item in sublist:
            return lists.index(sublist), sublist.index(item)

>>> L=[[1,2,3],[4,5,6]]
>>> get_sublist_index(L, 3)
(0, 2)

或者获取每个项目:

def get_sublist_index(lists, item):
    for sublist in lists:
        if item in sublist:
            yield lists.index(sublist), sublist.index(item)

制作生成器
>>> L=[[1,2,3],[4,3,6]]
>>> get_sublist_index(L, 3)
<generator object get_sublist_index at 0x1056c5e08>
>>> [i for i in get_sublist_index(L, 3)]
[(0, 2), (1, 1)]

或者如果您不想使用生成器:

def get_sublist_index(lists, item):
    outList = []
    for sublist in lists:
        if item in sublist:
            outList.append((lists.index(sublist), sublist.index(item)))
    return outList

>>> get_sublist_index(L, 3)
[(0, 2), (1, 1)]
>>> 

这只返回您找到的第一项,除非这就是 OP 想要的。 - MooingRawr
@MooingRawr 谢谢。我会修改它。 - rassar

3
L=[[1,2,3],[4,5,6],[2,3,4,5,3]]

a = 3

print([(i,j) for i,x in enumerate(L) if a in x for j,b in enumerate(x) if b == a])
#[(0, 2), (2, 1), (2, 4)]

使用列表推导式可以挖掘并返回所有子值。如果需要更深入,请继续链接列表推导或编写一个函数来完成。

2
也许是这样的:

也许是类似于这样:

def find_sublist(outer, what):
    for i, lst in enumerate(outer):
        try:
            return i, lst.index(what)
        except ValueError:
            pass

实际上,output = [0][2] 会抛出异常。我不确定您的意思是什么。您是否需要一个包含两个元素的元组?我将假设您确实需要。

您也可以使用更加优雅的方式,例如:

In [8]: [(i, sublist.index(3)) for i, sublist in enumerate(L) if 3 in sublist]
Out[8]: [(0, 2)]

In [9]: [(i, sublist.index(4)) for i, sublist in enumerate(L) if 4 in sublist]
Out[9]: [(1, 0)]

find_sublist(L, 3) only gives me an output of 0 and the OP says the output should be 0, 2 - rassar

2

使用 numpy.where numpy.transpose 方法的一行解决方案(初始输入数组已扩展以涵盖复杂情况):

import numpy as np

L = [[1,2,3],[4,3,6]]  # 3 occurs twice
output = np.transpose(np.where(np.array(L) == 3))

print(output)

输出结果:
 [[0 2]
  [1 1]]

如果列表中有多个相同的元素(例如 L = [[1,2,3],[4,3,6]]),则返回:array([[0, 1], [2, 1]]) - rassar
当他们想要返回 [place1x, place1y], [place2x, place2y] 时,它返回了 [place1x, place2x], [place1y, place2y] - rassar
@rassar,没错,我已经修复了,感谢你的提示。 - RomanPerekhrest

1

如果需要索引和序列,请始终使用enumerate

def find_index(l, val=3):
    # res holds results
    res = []
    # Go through every sublist in l 
    # index1 indicates which sublist we check
    for index1, sublist in enumerate(l):
        # Go through every item in sublist 
        # index2 indicates which item we check
        for index2, item in enumerate(sublist):
            # append to result if we find a match
            if item == val:
                res.append([index1, index2])
    return res

使用示例列表:

L = [[1, 2, 3], [4, 5, 6, 4, 3], [3, 3, 3]]

这段文字的意思是:这将返回:
find_index(L)
[[0, 2], [1, 4], [2, 0], [2, 1], [2, 2]]

0
考虑使用{{link1:more_itertools.locate}}返回索引字典。 代码
import more_itertools as mit


def indices(iterable, item):
    """Return a dict of indices of all located items."""
    d = {}
    for i, sub in enumerate(iterable):
        val = list(mit.locate(sub, lambda x: x == item))
        if not val:
            continue
        d[i] = val

    return d

演示

给定浅层嵌套的可迭代对象:

indices([[1, 2, 3], [5, 6, 7]], 3)
# {0: [2]}

indices([[1, 2, 3], [5, 6, 7], [2, 3, 3]], 3)
# {0: [2], 2: [1, 2]}

这里记录了多个出现的情况。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接