gpt4 book ai didi

python - 编写此 if 语句链是否更简单?

转载 作者:行者123 更新时间:2023-11-30 22:27:09 25 4
gpt4 key购买 nike

我正在制作战舰游戏,这段代码检查剩余的船只数量。我只知道使用 for 循环可以更轻松地完成它,但由于某种原因无法理解它。这是代码:

#empty Dictonary. This Dict will store the coords of the ship
boatDict = {'destroyer1': [], 'destroyer2': [],
'submarine1': [], 'submarine2': [],
'battleship': [], 'carrier': []}

if boatDict['destroyer1'] == []:
destroyer = 2
elif boatDict['destroyer1'] != []:
destroyer = 1
elif boatDict['destroyer2'] != []:
destroyer = 0

if boatDict['submarine1'] == []:
submarine = 2
elif boatDict['submarine1'] != []:
submarine = 1
elif boatDict['submarine2'] != []:
submarine = 0

if boatDict['battleship'] == []:
battleship = 1
elif boatDict['battleship'] != []:
battleship = 0

if boatDict['carrier'] == []:
carrier = 1
elif boatDict['carrier'] != []:
carrier = 0

提前致谢!

编辑:使问题和代码更清晰

最佳答案

我会创建一个船计数字典,如下所示:

boatDict = {'destroyer1': [3, 5], 'destroyer2': [7, 2],
'submarine1': [1, 1], 'submarine2': [],
'battleship': [], 'carrier': [5, 2]}

boatCount = {}

for key in boatDict:
if boatDict[key] != []:
boat = ''.join(i for i in str(key) if not i.isdigit())
if boat not in boatCount:
boatCount[boat] = 1
else:
boatCount[boat] += 1

print(boatCount)

#output

{'submarine': 1, 'carrier': 1, 'destroyer': 2}

因此创建一个空字典,b​​oat count。然后循环遍历boat dict,并为每个不与空列表关联的键创建一个名为boat 的变量。 Boat 变量将用作船计数字典的键。它还从 destroyer1 和 destroyer2 等键中删除数字,因为在新字典中,这些数字应该组合起来并简称为 destroyer。

下一个 if 语句检查新的船只变量是否存在于船只计数中。如果没有,它会创建一个新 key 并将该 key 的计数设置为 1。如果该键已存在,则 else 语句会将该键的计数加一。

更新为已全部被摧毁的船只显示 0:

boatDict = {'destroyer1': [3, 5], 'destroyer2': [7, 2],
'submarine1': [1, 1], 'submarine2': [],
'battleship': [], 'carrier': [5, 2]}

boatCount = {}

for key in boatDict:
boat = ''.join(i for i in str(key) if not i.isdigit())
if boat in boatCount:
if boatDict[key] != []:
boatCount[boat] += 1
else:
if boatDict[key] != []:
boatCount[boat] = 1
else:
boatCount[boat] = 0

print(boatCount)

#output

{'destroyer': 2, 'battleship': 0, 'submarine': 1, 'carrier': 1}

关于python - 编写此 if 语句链是否更简单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47023467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com