python - 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 循环并重新生成,直到它们对它们的列表来说是唯一的。
我是初学者,所以如果我有明显的失误请不要评判。谢谢
解决方案
if ships['shiprows'][temp] in ships['shiprows'] and ships['shipcols'[temp] in ..
^^^^
unmatched brackets
你的变量 vars 也被你的 for 循环中的变量所掩盖。
推荐阅读
- python - 有没有办法分析分类变量对python中标签的影响/相关性?
- c# - 证明两个列表(包含对象)内容相等的最简单方法
- content-security-policy - 带有事件处理程序哈希的内容安全策略在 iOS Safari 上不起作用
- html - 为什么我不能使用导入 svg
- javascript - 如何使用脆标签更改颜色帮助文本
- visual-studio-code - 取消隐藏 Visual Studio Code 活动栏中的“运行和调试”选项
- c# - C# 在项目中断后停止正常工作
- java - Android Studio北极狐中的Circleprogress问题
- jquery - 未捕获的 TypeError JS
- variables - 从外部 js 重新构建变量名