python - 如何在 Python 列表列表中找到项目的位置?

标签 python

我想在列表列表中查找特定项目的位置。它应该返回一个元组列表,其中每个元组代表项目特定实例的索引。例如:

list = [['1', '2', '4', '6'], ['7', '0', '1', '4']]
getPosition('1')  #returns [(0, 0), (1, 2)]
and getPosition('7') #returns [(1,0)]

最佳答案

如果你想要两者兼得的东西

  • 查找重复项和
  • 处理嵌套列表(......列表的列表列表)

您可以执行以下操作:

def get_positions(xs, item):
    if isinstance(xs, list):
        for i, it in enumerate(xs):
            for pos in get_positions(it, item):
                yield (i,) + pos
    elif xs == item:
        yield ()

测试这个:

>>> xs = [['1', '2', '4', '6'],
...       ['7', '0', '1', '4'],
...       [ [ '0', '1', '1'], ['1']]
...       ]
>>> print list(get_positions(xs, '1'))
[(0, 0), (1, 2), (2, 0, 1), (2, 0, 2), (2, 1, 0)]

关于python - 如何在 Python 列表列表中找到项目的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/853023/

相关文章:

python - 如何使用自定义 CTC 层正确保存和加载模型(Keras 示例)

python - 如何与其他json对象的值进行比较

python - 强制 numpy 保留一个列表

python - YAML 中未解释的字符串

python - 从一维 numpy 数组中有效地切片窗口,围绕第二个二维数组给出的索引

python - 无法调用 Waf - ImportError : cannot import name Scripting

python - pandas-将系列添加到数据框会导致出现 NaN 值

python - 有没有办法改变ezdxf中的背景颜色?

python - numpy/ Pandas : How to convert a series of strings of zeros and ones into a matrix

javascript - 如何获取 Bokeh 热图中点击位置的标签