簡體   English   中英

在嵌套列表中查找元素索引

[英]finding the index of elements in nested list

我正在嘗試創建一個程序,它將在嵌套列表中查找並存儲每個元素的索引。

到目前為止,我已經嘗試使用嵌套的迭代器來完成此任務。

以下是我的代碼。

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

我認為行索引以正確的方式輸出,但列索引做了一些奇怪的事情。

我已多次查看代碼,但我無法找出它的錯誤。

使用enumerate的嵌套理解將執行:

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始終返回列表中元素的第一個索引,因此如果有重復,它將無法工作。 此外,它的性能更差,因為每個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

如果你知道你的表沒有鋸齒 ,你可以使用itertools.product

from itertools import product

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

這是一個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)]

如果仔細觀察,那么您可能會發現列表中存在重復值,這是導致索引錯誤的原因。 因此,如果是重復,您可以使用枚舉。 枚舉將返回元組對象,因此對它進行迭代,這將為您提供預期的輸出。

你可以嘗試這個 -

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM