簡體   English   中英

如何在Python中查找列表行和列索引

[英]How to find list rows and columns index in Python

我正在嘗試在列表中打印行索引和列索引。

我已經使用(下面的循環),但是它一個或另一個。

a = [[0,0,1],
    [0,1,0],
    [1,0,0]]
def a():
x = 0
for sol in solutions:
    print(sol)
    for row in sol:
        print(row)

我正在嘗試打印
(0,2)(1,1)(2,0)
1s索引
謝謝

您可以使用enumerate為列表生成索引:

for row, sublist in enumerate(a):
    for column, item in enumerate(sublist):
        if item:
            print((row, column))

輸出:

(0, 2)
(1, 1)
(2, 0)

如果您喜歡numpy,則可以將其轉換為numpy數組,並使用argwhere()

import numpy as np
a = [[0,0,1],
    [0,1,0],
    [1,0,0]]

a = np.array(a)
answer = np.argwhere(a==1)

這將輸出:

[[0 2]
 [1 1]
 [2 0]]

暫無
暫無

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

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