Python:在列表中查找内容

时间:2016-12-26 15:45:07

标签: python python-3.x

def
    for i in play.inventory:
        if "Sword" in i and "[S]lash" not in abilities:
            abilities.append("[S]lash")
        elif "Bow" in i and "[F]ire" not in abilities:
            abilities.append("[F]ire")
        elif "Fists" in i and "[P]unch" not in abilities:
            abilities.append("[P]unch")
        elif "Legs" in i and "[K]ick" not in abilities: 
            abilities.append("[K]ick ")
        return abilities

所以目前我从我的一个单独的问题中得到了这个代码但是在使用它的时候大部分内容都很顺利,除了它只识别" Fists" (列表是[' Fists',' Legs'])如果Sword尚未触发它,我还没有尝试过,但我想先修好这个,预期结果应该是:

abilities = ["[K]ick","[P]unch"]

然后我用它打印出来:

 for a in aca:
    print(a)

aca的能力。

目前它的结果如下:

for a in aca:
    print(a)
>>[P]unch

使用PyCharm CE,Python 3.5.2

根据要求: play.inventory是一个类的对象(我认为?)代码:

class Player:
    def __init__(self):
        self.inventory = []

play = Player()

1 个答案:

答案 0 :(得分:0)

你应该删除elif,只需使用if, set 也可以帮到你。

    abilities = set(abilities) #this will make each item appear only once...
    if "Sword" in play.inventory:
        abilities.add("[S]lash")
    if "Bow" in play.inventory:
        abilities.add("[F]ire")
    if "Fists" in play.inventory:
        abilities.add("[P]unch")
    if "Legs" in play.inventory:
        abilities.add("[K]ick ")
    return list(abilities)

你也可以在一个循环中完成

    i2a = {"Sword": "[S]lash",
           "Bow": "[F]ire",
           "Fists": "[P]unch",
           "Legs": "[K]ick"}
    for i, a in i2a.items():
        if i in play.inventory:
           abilities.append(a)
    return list(set(abilities)) #another way to remove duplicates...