首页 > 解决方案 > 使用 ID 检索二维数组数据

问题描述

基本上我正在创建一个小型乐透程序,我想做一个功能,用户可以输入他/她的 id,它会给出他们的号码并让他们知道他们是否是赢家

玩家号码存储在一个二维数组**(不是 numpy)** 中,[[2, 17, 19, 19, 21, 29, 8, 17],[9, 5, 17, 18, 23, 28, 2, 2]]所以如果玩家输入他们的号码,id as 1那么它应该完全返回第二个数组,因为我想检查那个玩家是否是赢家。

我已经完成了以下操作,但它不起作用,当我单独运行播放器检查部分时它确实起作用

IndexError: list index out of range

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]]
win = [2, 17, 19, 19, 21, 29, 8, 17]
group1 = set(win[0:6])
group2 = set(win[6:8])
playerID = int(input("Please enter player ID "))
print(playerID)
print(player[playerID])
for i in player[playerID]:
    count = 0
    for j in range(6):
        x = player[i][j]
        if x in group1:
            count+=1
            print("score")
        if j == 5:
            if count == 6:
                print("You are a winner")
            elif count == 5:
                print("You win with 5 numbers" )
            elif count == 4:
                print("You win with 4 numbers")
            elif count == 3:
              print(  "you win with 3 numbers")
            elif count < 3:              
                    count2 = 0
                    for l in range(6,8):
                        y = player[i][l]
                        if y in group2:
                            print("you win with bouns numbers")
            else: 
                print("sorry you lose")
            

 

标签: pythonarraysmultidimensional-array

解决方案


一开始你让我很困惑。您使用的不是数组,而是列表列表。数组是python中特定的东西(来自数组模块),并且总是一维的。

话虽如此,您的代码(使用列表列表)是正确的。如果用户键入并且 ID >3,您只会收到错误消息。


推荐阅读