首页 > 解决方案 > Python检查数字是否已经在列表中,该列表是字典中的一个值,是否重新生成直到它不同 - 语法错误

问题描述

我正在尝试为战舰游戏中的船只生成唯一坐标。我尝试了很多东西,但要么出现语法错误,要么超出范围。我意识到:

my_dict = {key : [1, 2, 3], key2 : [4, 5, 6]}
x = 2
print(mydict['key'][x - 1])

不会给我no1索引。我的代码片段在这里:编辑:添加了缺失的东西。

from random import *
board = []

for x in range(0, 10):
  board.append(["O"] * 10)


ships = {
'shiprows': [0],
'shipcols' : [0]
}

def random_row1(board):
  return randint(0, len(board) - 1)

def random_col1(board):
 return randint(0, len(board) - 1)

vars = 0
temp = 0
for vars in range(0, 5):
  print(vars)
  if len(ships['shiprows']) >= 2 and len(ships['shipcols']) >= 2:
    temp = vars - 1
    if ships['shiprows'][temp] in ships['shiprows'] and ships['shipcols'[temp] in ships['shipcols']:
      print("if loop")

    ships['shiprows'].append(random_row1(board))
    ships['shipcols'].append(random_col1(board))
  else:
    ships['shiprows'].append(random_row1(board))
    ships['shipcols'].append(random_col1(board))
    vars = vars + 1
  print(ships)

代码只是处于调试状态 - 我试图让数字进入所说的狡猾的 if 循环并重新生成,直到它们对它们的列表来说是唯一的。

我是初学者,所以如果我有明显的失误请不要评判。谢谢

标签: pythonlistdictionaryif-statement

解决方案


if ships['shiprows'][temp] in ships['shiprows'] and ships['shipcols'[temp] in ..
                                                                  ^^^^
                                                               unmatched brackets

你的变量 vars 也被你的 for 循环中的变量所掩盖。


推荐阅读