所以,我试图在字符列表中搜索任何重复的名称,这样就可以避免添加重复的名称。我不确定如何在不使用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
使用
set
跟踪名称:您的字符列表是字符列表,而不是字符名列表。按照现在的编写方式,检查当前名称是否在字符列表中是没有意义的(您要在包含字符对象的列表中查找字符串)
另外,您不希望角色的属性(名称、修饰符等)是静态变量(属于该类的变量,而不是该类的实例)
编辑*我建议避免使用静态变量并不是那么重要。与其他语言不同,python区分了类级变量和实例级变量。例如:
输出:
不过,我还是建议显式地让它们成为实例变量。顺便说一下,您可以将“character\u creator”代码移到类的
__init__
方法中。我认为使用一组取下来的名字来防止自己添加一个重复的名字可以避免代码出现更深层次的问题(我知道这不是代码评审板,哦)。我建议使用类级别集(本例中可用的\u名称)并从中弹出任意元素,直到用尽为止(此时抛出异常):输出:
相关问题 更多 >
编程相关推荐