编写if语句链的更简单方法是什么?

时间:2017-10-30 20:14:06

标签: python

我正在制作一艘战列舰游戏,这段代码会检查剩余的船只数量。我只知道使用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

提前致谢!

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

3 个答案:

答案 0 :(得分:2)

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

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}

所以创建一个空字典,船数。然后循环遍历船只字典,并且对于与空列表无关的每个键,创建一个名为boat的变量。船变量将用作船计数字典的关键。它还从诸如destroyer1和destroyer2之类的键中删除数字,因为在新词典中,这些应该被组合并简称为驱逐舰。

下一个if语句检查船只计数中是否存在新的船只变量。如果没有,则创建一个新密钥并将该密钥的计数设置为一。如果密钥已经存在,那么else语句会为该密钥的计数添加一个。

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

MyObj myObj = myObjService.getById(465);
Assert.assertNotEquals("newValue1", myObj.getX());
Assert.assertNotEquals("newValue2", myObj.getY());

答案 1 :(得分:1)

作为布尔值,空列表为false,非空列表为true。此外,布尔值TrueFalse实际上只是伪装的整数1和0。因此,您只需编写

即可
destroyers = sum(bool(boatDict[x]) for x in 'destroyer1', 'destroyer2')
submarines = sum(bool(boatDict[x]) for x in 'submarine1', 'submarine2')

battleships = int(bool(boatDict['battleship']))
carrier = int(bool(boatDict['carrier']))

答案 2 :(得分:0)

假设boatList是一个字典,你可以获得已经消除了多少驱逐舰

destroyersEliminated = 0
for k, v in boatList.items(): #in py2, use iteritems()
    if k in ["destroyer1", "destroyer2"] and v != []:
        destroyersEliminated += 1

然后你可以从驱逐舰的总数中减去它:

destroyers = totalDestroyers = destroyersEliminated

您也可以选择使用列表推导来执行此操作:

destroyersEliminated = len(k for k in boatList 
    if k in ["destroyer1", "destroyer2"]
    and boatList[k] != [])

旁注:有很多方法可以使这个更清洁,包括采用面向对象的方法,其中每艘船是一个具有类型和状态的对象;然后,您就可以遍历它们的列表并检查它们的类型和状态以获得计数。