python - 在二维 Python 数组中查找元素

标签 python arrays list numpy multidimensional-array

我想做的是获取用户输入的任意数量的行,并将其放入数组中。之后我想找到数组中最大数字的位置,即数字类型的 (x,y) 坐标。我以不同的方式创建了初始数组,但例如我有:

  import numpy as np
  m = []
  rows = eval(input("How many rows in the list:"))
  for row in range(rows):
      m.append([])
      value = eval(input("Enter a row:"))
      m[row].append(value)
  m = np.array(m)
  print(m)
  M = np.amax(m)
  print(M)
  index = np.where(M)
  print(index)  

打印只是为了让我可以看到它在做什么。最后我只想看看这个例子中的最后一行:

   Enter the number of rows in the list:3          
   Enter a row: 1,5,6        
   Enter a row: 2,6,7     
   Enter a row: 5,26,12     
   The location of the largest element is at (1, 2)

额外信息:我不在乎它是否使用 numpy 或 not。我不会反对使用单独的函数,当我想到这可能是一个好主意;一个用于创建数组,另一个用于定位最大的数字。

提前致谢。

PS。正如评论所说,由于安全风险,通常不应使用 eval。我使用它的唯一原因是因为这是学校的快速作业。

最佳答案

这是一个不使用numpy的实现。虽然效率不高,但效果很好。

rows = eval(input("How many rows in the list:"))
m = []
for row in range(rows):
  value = eval(input("Enter a row:"))
  m.append(value)

large = m[0][0]
x = 0
y = 0

for i in range(0, rows):
  for j in range(0, len(m[i])):
    if(large < m[i][j]):
     large = m[i][j]
     y = i
     x = j
print(x, y, large)

关于python - 在二维 Python 数组中查找元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40838340/

相关文章:

python - 有没有一种方法可以使用用户定义的距离度量来选择 scikits 中的 k 个最近邻居?

python - 使用 networkx 绘制多路复用图?

javascript - 通过javascript中的另一个对象数组对对象数组进行排序

python - 在不同数组的一定范围内的元素中从一个数组中查找元素

python - iPython notebook 无法连接到 google-compute-engine 上的内核

python - 当服务器没有响应时在 Python 中中止 GET 请求

Javascript 游戏自动创建新对象以连续添加到数组中 [javascript]

c++ - 搜索列表中的最后一个数据实例

python - 有什么方法可以使用列表理解从列表中创建集合吗?

python - 查找列表中的最小元素(递归) - Python