如何使用“If char.name in list \u of \u chars:”来扫描\u of \u chars列表中对象的变量名?

2024-05-15 00:47:37 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我试图在字符列表中搜索任何重复的名称,这样就可以避免添加重复的名称。我不确定如何在不使用for循环的情况下做到这一点,因为for循环并不理想

我在Windows10上的idle中使用Python3.7.3。我尝试使用list\u of \u chars.name,但这不起作用。我试着把它放入for循环中,逐个搜索每个object.name,但结果列表中的所有内容都翻了一番

class character:
    name = ""
    boldness_mod = 1
    wealth_mod = 1
    def describe_char(self):
        print("%s is a player with %d boldness and %d wealth" % (self.name, self.boldness_mod, self.wealth_mod))

def character_creator():
    name_bank = [
        "Jim", "Kyle", "Malinda", "Wheat", "Whispering River", "Thunderous Fall", "Megalodon", "Morpheus"
        ]
    char = character()
    mod1 = random.randint(1,10)
    mod2 = random.randint(1,4)
    mod3 = random.randint(0,len(name_bank)-1)
    char.boldness_mod = mod1
    char.wealth_mod = mod2
    char.name = name_bank[mod3]
    return char

def run_game(number_of_ai, starting_money):
    list_of_chars = []
    for i in range(number_of_ai):
        char = character_creator()
        #for i in range (len(list_of_chars)):
        #    if char.name in list_of_chars[i].name:
        #        continue
        #    list_of_chars.append(char)
        if char.name in list_of_chars:
            continue
        list_of_chars.append(char)
    for i in range(len(list_of_chars)):
        list_of_chars[i].describe_char()

所以,预期的输出是这样的

Jim is a player with 6 boldness and 3 wealth
Morpheus is a player with 6 boldness and 4 wealth
Whispering River is a player with 7 boldness and 4 wealth
Thunderous Fall is a player with 5 boldness and 2 wealth

我们的愿望是永远不要让任何角色有相同的名字。当我尝试将注释掉的for循环放入时,结果如下所示

Megalodon is a player with 2 boldness and 1 wealth
Malinda is a player with 4 boldness and 3 wealth
Malinda is a player with 4 boldness and 3 wealth
Jim is a player with 1 boldness and 3 wealth
Jim is a player with 1 boldness and 3 wealth
Jim is a player with 1 boldness and 3 wealth
Jim is a player with 1 boldness and 3 wealth
Morpheus is a player with 8 boldness and 4 wealth
Morpheus is a player with 8 boldness and 4 wealth
Morpheus is a player with 8 boldness and 4 wealth
Morpheus is a player with 8 boldness and 4 wealth
Morpheus is a player with 8 boldness and 4 wealth
Morpheus is a player with 8 boldness and 4 wealth
Morpheus is a player with 8 boldness and 4 wealth
Morpheus is a player with 8 boldness and 4 wealth

Tags: andofnamemodforiswithlist
2条回答

使用set跟踪名称:

def run_game(number_of_ai, starting_money):
    list_of_chars = []
    char_names = set()
    for i in range(number_of_ai):
        char = character_creator()
        if char.name in char_names:
            continue
        list_of_chars.append(char)
        char_names.add(char.name)
    for i in range(len(list_of_chars)):
        list_of_chars[i].describe_char()

您的字符列表是字符列表,而不是字符名列表。按照现在的编写方式,检查当前名称是否在字符列表中是没有意义的(您要在包含字符对象的列表中查找字符串)

另外,您不希望角色的属性(名称、修饰符等)是静态变量(属于该类的变量,而不是该类的实例)

编辑*我建议避免使用静态变量并不是那么重要。与其他语言不同,python区分了类级变量和实例级变量。例如:

class Character:
    name = "Default Name"


def main():

    char = Character()
    char.name = "Bob"

    print(char.name)
    print(Character.name)

    return 0

if __name__ == "__main__":
    from sys import exit
    exit(main())

输出:

Bob
Default Name

不过,我还是建议显式地让它们成为实例变量。顺便说一下,您可以将“character\u creator”代码移到类的__init__方法中。我认为使用一组取下来的名字来防止自己添加一个重复的名字可以避免代码出现更深层次的问题(我知道这不是代码评审板,哦)。我建议使用类级别集(本例中可用的\u名称)并从中弹出任意元素,直到用尽为止(此时抛出异常):

class Character:

    available_names = {"Tom", "Jerry", "Laura", "Nigel", "Bob", "Robert", "Tom"}

    def __init__(self):
        from random import randint

        if not Character.available_names:
            raise RuntimeError("No more names available!")

        next_name = Character.available_names.pop()

        self.name = next_name
        self.strength = randint(0, 10)

    def get_info(self):
        return f"My name is {self.name} and my strength is {self.strength}."


def main():

    number_of_characters = 3

    characters = [Character() for _ in range(number_of_characters)]

    for character in characters:
        print(character.get_info())

    return 0

if __name__ == "__main__":
    from sys import exit
    exit(main())

输出:

My name is Jerry and my strength is 4.
My name is Robert and my strength is 7.
My name is Tom and my strength is 3.

相关问题 更多 >

    热门问题