【问题标题】:finding the index of elements in nested list查找嵌套列表中元素的索引
【发布时间】:2018-11-15 12:25:25
【问题描述】:

我正在尝试创建一个程序来查找并存储嵌套列表中每个元素的索引。

到目前为止,我已经尝试使用嵌套的 for 迭代器来完成此操作。

下面是我的代码。

table = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
def coordinates(table):
    target_cell_list = []
    for row in table:
        for column in row:
            target_cell = (table.index(row), row.index(column))
            target_cell_list.append(target_cell)
    return target_cell_list

>>> table = [[1, 1, 1], [2, 2, 3], [2, 3, 3]]
>>> coordinates(table)
# current output
[(0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (1, 2), (2, 0), (2, 1), (2, 1)]

# desired output
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

我认为行索引以正确的方式输出,但列索引却在做一些奇怪的事情。

我已经检查了好几次代码,但我找不到它有什么问题。

【问题讨论】:

  • 你得到那个输出是因为例如在第一行你有三列有相同的数字,所以它总是检索索引0。

标签: python python-3.x python-2.7


【解决方案1】:

使用enumerate 的嵌套comprehension 可以:

table = [[1, 1, 1], [2, 2, 3], [2, 3, 3]]

def coordinates(tbl):
    return [(i, j) for i, row in enumerate(tbl) for j, _ in enumerate(row)]
    # or a little shorter
    # [(i, j) for i, row in enumerate(tbl) for j in range(len(row))]

coordinates(table)
# [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

您基于list.index(elmnt) 的方法失败了,因为index 总是返回列表中元素的first 索引,因此如果有重复,它将不起作用。此外,它的性能更差,因为每个index 调用都必须迭代它所调用的列表。 一个纯循环索引的实现沿着你原来的路线是:

def coordinates(tbl):
    target_cell_list = []
    for i in range(len(tbl)):
        for j in range(len(tbl[i])):
            target_cell_list.append((i, j))
    return target_cell_list

如果你知道你的表不是jagged,你可以使用itertools.product:

from itertools import product

def coordinates(tbl):
    return list(product(range(len(tbl)), range(len(tbl[0]))))

【讨论】:

    【解决方案2】:

    这是numpy 解决方案。

    >>> import numpy as np
    >>> list(zip(*np.where(np.ones_like(table))))                                                                     
    [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
    

    【讨论】:

      【解决方案3】:

      如果您仔细观察,您可能会发现列表中存在重复值,这就是您获取错误索引的原因。因此,如果出现重复,您可以使用枚举。 Enumerate 将返回元组对象,因此对其进行迭代,这将为您提供预期的输出。

      你可以试试这个-

      def coordinates(table):
          target_cell_list = []
          for i,row in enumerate(table):
              for j in range(len(row)):
                  target_cell = (i,j)
                  target_cell_list.append(target_cell)
          return target_cell_list
      table = [[1, 1, 1], [2, 2, 3], [2, 3, 3]]
      print(coordinates(table))
      

      【讨论】:

        猜你喜欢
        • 2013-01-17
        • 2016-02-29
        • 1970-01-01
        • 2011-01-25
        • 1970-01-01
        • 2023-02-04
        • 2023-02-06
        • 2016-04-19
        • 1970-01-01
        相关资源
        最近更新 更多