Python 在带条件的2d列表中查找索引
我需要在2d数组中找到索引,其中的数字要么大于左边和右边的数字,要么小于上面和下面的数字,反之亦然 我知道我需要两个循环,一个循环用于列,一个循环用于行,我得到了数字x,我需要将其与2d数组中的数字进行比较以找到索引Python 在带条件的2d列表中查找索引,python,arrays,algorithm,list,Python,Arrays,Algorithm,List,我需要在2d数组中找到索引,其中的数字要么大于左边和右边的数字,要么小于上面和下面的数字,反之亦然 我知道我需要两个循环,一个循环用于列,一个循环用于行,我得到了数字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,我需要在2
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语句检查大于小于的问题。这样可以吗
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
运行示例:
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
运行示例:
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
(在第三个示例中,对于x=6,没有结果,给定条件中的任何一个都不满足2d列表中的任何位置)。不是家庭作业服务,请给我们提供一个尝试性的解决方案。尝试添加到问题中非常感谢Tkhuraa96,它看起来与我正在寻找的非常接近for@mcfellows如果对你有帮助,那就太好了