如何从另一个列表中的列表中获取坐标元组

问题描述 投票:0回答:1

我有以下清单:

list = [[0, 0, 1], 
        [1, 0, 0], 
        [0, 1, 0]]

我的目标是从此列表中返回一组元组,其中包含等于

1
的每个值的坐标(行、列)。

上述代码的正确答案是:

{(0, 2), (1, 0), (2, 1)}

我正在研究我的列表理解知识。我设法使用

for
循环和索引来做到这一点,但我想要更干净的代码。如果解决方案可以使用列表理解,我将不胜感激

python list indexing list-comprehension coordinates
1个回答
0
投票

这是实现您想要的

set
的理解:

my_list = [
    [0, 0, 1],
    [1, 0, 0],
    [0, 1, 0]
]

coordinates = set(
    (row, column)
    for row in range(len(my_list))
    for column in range(len(my_list[row]))
    if my_list[row][column] == 1
)
print(coordinates)

这应该打印:

{(1, 0), (0, 2), (2, 1)}
© www.soinside.com 2019 - 2024. All rights reserved.