【问题标题】:Finding indexes in 2d list with conditionals使用条件查找二维列表中的索引
【发布时间】:2017-07-23 22:31:21
【问题描述】:

我需要在二维数组中找到索引,其中数字要么大于左右的数字,要么小于上下的数字,反之亦然。

我知道我需要两个 for 循环,一个用于列,一个用于行,我得到数字 x,我需要将它与 2d 数组中的数字进行比较以查找索引。

list = [[1,4,6,7,8],
        [2,4,6,7,8],
        [1,4,6,7,8],
        [1,4,6,7,8],
        [2,4,6,7,8],
        [6,4,6,7,8]]

如果给定 4 作为 x,我需要在 2d 列表中找到左侧、右侧、向上和向下的索引,反之亦然,其他数字大于或小于 4。有人可以提供一个解决方案

list = [[1, 4, 6, 7, 8],
        [2, 4, 6, 7, 8],
        [1, 4, 6, 7, 8],
        [1, 4, 6, 7, 8],
        [2, 4, 6, 7, 8],
        [6, 4, 6, 7, 8]]

x = [x for x in list if 4 in x][0]
print('The index is (%d,%d)' % (list.index(x), x.index(4)))

通过这种尝试,它只会给我第一个索引,但我需要检查整个数组并使用 if 语句来检查大于小于问题。

【问题讨论】:

  • 不是功课服务,半路来找我们尝试解决方案。
  • 尝试添加到问题中

标签: python arrays algorithm list


【解决方案1】:

这样可以吗?...

x = int(input('Enter x: '))
data = [[1, 4, 6, 7, 8],
        [2, 4, 6, 7, 8],
        [1, 4, 6, 7, 8],
        [1, 4, 6, 7, 8],
        [2, 4, 6, 7, 8],
        [6, 4, 6, 7, 8]]

dataTranspose = list(zip(*data))

for each_row_number in range(0, len(data)):

    tempRow = list(enumerate(data[each_row_number]))
    maxIndex, maxVal = max(tempRow, key=lambda eachPair: eachPair[1])
    minIndex, minVal = min(tempRow, key=lambda eachPair: eachPair[1])

    if x == maxVal:
        if x == min(dataTranspose[maxIndex]):
            print(' found another at: (' + str(each_row_number) + ', ' + str(maxIndex) + ')')
    elif x == minVal:
        if x == max(dataTranspose[minIndex]):
            print(' found another at: (' + str(each_row_number) + ', ' + str(minIndex) + ')')

示例运行:

Enter x: 8
 found another at: (0, 4)
 found another at: (1, 4)
 found another at: (2, 4)
 found another at: (3, 4)
 found another at: (4, 4)
 found another at: (5, 4)

示例运行:

Enter x: 4
 found another at: (5, 1)

示例运行:

Enter x: 6

(在第 3 个示例中没有结果,因为 x = 6,任何一个给定条件都不满足 2d 列表中的任何位置)。

【讨论】:

  • 非常感谢 tkhurana96,这看起来就是我要找的东西
  • @mcfellows 如果对您有帮助,那就太好了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-21
  • 2021-05-17
  • 1970-01-01
  • 2021-02-03
  • 2019-07-05
  • 1970-01-01
相关资源
最近更新 更多