如何搜索2D数组并返回元素

时间:2020-10-01 18:32:51

标签: python arrays

在我的程序中,我希望用户输入一个数字,然后搜索该数字并返回2D数组中的元素。

for example if input = 1 then array[1][1,2,3,4,5,6] and separately array[1][7,8]

player = [[2, 17, 19, 19, 21, 29, 8, 17],[9, 5, 17, 18, 23, 28, 2, 2],[5, 8, 18, 18, 29, 30, 25, 26],[5, 6, 15, 13, 23, 24, 12, 12]]
playerID = int(input("Please enter player ID "))
print(playerID)
for i in array(playerID):
   for j in array(6):
       print(array[i][j])
else:
   print("not found")
pseudocode

get playerID 
print playerID
search for playerID in player
    access the elements upto 6 
        print player[playerID] [player's Elements] 
else
    print not found
      

1 个答案:

答案 0 :(得分:0)

player = [[2, 17, 19, 19, 21, 29, 8, 17],[9, 5, 17, 18, 23, 28, 2, 2],[5, 8, 18, 18, 29, 30, 25, 26],[5, 6, 15, 13, 23, 24, 12, 12]]
playerID = int(input("Please enter player ID "))
for p in player:
    if playerID in p[:6]:
        print([playerID],p[:6])
        print([playerID],p[6:])

输出

Please enter player ID 5
[5] [9, 5, 17, 18, 23, 28]
[5] [2, 2]
[5] [5, 8, 18, 18, 29, 30]
[5] [25, 26]
[5] [5, 6, 15, 13, 23, 24]
[5] [12, 12]