查找多个列表中的值

3 投票
5 回答
1150 浏览
提问于 2025-04-17 09:14

我正在用Python写一个程序,这个程序会查看一个列表中的列表,并且修改里面的值。

在我的这个列表中,有一些数字3,我想找到它们的位置。现在我的程序只能在第一行找到3的位置。我希望它能在“numbers”中的任何列表里找到3。

这里有一些示例代码,帮你理解:

numbers = [
    [3, 3, 3, 5, 3, 3, 3, 3, 6],
    [8, 0, 0, 0, 4, 7, 5, 0, 3],
    [0, 5, 0, 0, 0, 3, 0, 0, 0],
    [0, 7, 0, 8, 0, 0, 0, 0, 9],
    [0, 0, 0, 0, 1, 0, 0, 0, 0],
    [9, 0, 0, 0, 0, 4, 0, 2, 0],
    [0, 0, 0, 9, 0, 0, 0, 1, 0],
    [7, 0, 8, 3, 2, 0, 0, 0, 5],
    [3, 0, 0, 0, 0, 8, 0, 0, 0],
    ]
a = -1
while a:
    try:
        for row in numbers:
            a = row[a+1:].index(3) + a + 1
            print("Found 3 at index", a)
    except ValueError:
        break

当我运行这段代码时,我得到:

Found 3 at index 0
Found 3 at index 1
Found 3 at index 2
Found 3 at index 4
Found 3 at index 5
Found 3 at index 6
Found 3 at index 8

这说明程序在运行,但只在第一行找到了结果。

谢谢!

5 个回答

1

试试下面这个:

[[i for i, v in enumerate(row) if v == 3] for row in numbers]

这样做会得到一个列表的列表,其中每个内部列表里的内容都是原始列表中对应行里数字3的位置索引:

[[], [8], [5], [], [], [], [], [3], [0]]

你说你在找数字3,但你的代码看起来是在找数字0,你到底想找哪个呢?

你可以这样使用它:

threes = [[i for i, v in enumerate(row) if v == 3] for row in numbers]
for row, indices in enumerate(threes):
    for col in indices:
        print "3 found in row %d, column %d" % (row, col)
2

如果你只想获取行的索引,可以用 enumerate 来遍历 numbers,同时用 in 来检查列表里是否有 3

for index, row in enumerate(numbers):
    if 3 in row:
        print "3 found in row %i" % index

如果你想获取行和列的索引,就要同时遍历两个列表:

for index, row in enumerate(numbers):
    for col, value in enumerate(row):
        if value == 3:
            print "3 found in row %i at position %i" % (index, col)

如果你只是想把索引放到一个新的列表里,可以使用 列表推导式 [docs]

indexes = [(row, col) for row, r in enumerate(numbers) for col, val in enumerate(r) if val == 3]
2

这里有一段简单的代码,可以帮助你入门:

>>> for i, row in enumerate(numbers):
        if 3 in row:
            print i, row.index(3)   

1 8
2 5
7 3
8 0

>>> numbers[1][8]
3
>>> numbers[2][5]
3
>>> numbers[7][3]
3
>>> numbers[8][0]
3

撰写回答