我正在尝试使用 python 创建一个字符选择 CLI。
我想显示用户当前选择的角色队伍,以便他们可以看到他们已经选择了谁。用户不能两次选择相同的字符。用户必须有 4 个字符才能继续
我创建了以下代码(我确实正确调用了它,不用担心!):
def ChooseCharacters():
CharList=[]
CurrentParty=[]
print("Select up to 4 explorers!")
while len(CharList)!=4:
if len(CharList)!=4:
if len(CharList)==0:
pass
else:
for CharID in list(set(CharList)):
print(CharList)
SQL=("SELECT firstname,secondname FROM characters WHERE CharID=%s")
mycursor.execute(SQL,(CharID,))
myresult=mycursor.fetchone()
Name=(myresult[0]+" "+myresult[1])
CurrentParty= list(set(CurrentParty))
CurrentParty.append(Name)
print("Current Party: ",CurrentParty)
PrintChoice(CharList)
def PrintChoice(CharList):
mycursor.execute("SELECT * FROM characters")
myresults=mycursor.fetchall()
Num=0
for char in myresults:
Num = Num + 1
print(str(Num)+("."),char[1],char[2])
Choice=input("Select Character: ")
if Choice in CharList:
print("Character already selected!")
return
CharList.append(Choice)
print(CharList)
看起来所选的第一个字符在列表中重复,其余代码工作正常。
预期结果
Current Party: ['Sam Jordan']
Current Party: ['Sam Jordan','Olivia Cope']
Current Party: ['Sam Jordan','Olivia Cope','Dylan Nesbitt']
实际结果
Current Party: ['Sam Jordan']
Current Party: ['Olive Cope', 'Sam Jordan', 'Sam Jordan']
Current Party: ['Sam Jordan', 'Olive Cope', 'Dylan Nesbitt', 'Sam Jordan']
我无法确定第一个输入的第二次复制发生在哪里,因为第一个输入输出正确。
如果您需要查看数据库表,请询问。
最佳答案
您当前的代码有点难以理解,因为它混合了非常不同类型的事件:从数据库读取、让用户交互式地做出选择以及常规算法逻辑。此外,代码依赖于一种通常最好尽可能避免的模式——即将数据结构传递给其他函数,以便其他函数可以修改它们。编写获取数据并返回新数据的函数通常更简单,也是明智的做法。
我建议您重构它以进行一些更清晰的分离,而不是困惑如何修复当前的代码。这是一个快速说明:
import string
# A top-level function to orchestrate things.
def choose_characters():
chars = get_characters_from_db(12) # Read 12 from DB.
selected = select_items(chars, 4) # Select 4 of them.
print(selected)
# One or more functions to interact with the database.
# In this example we just return some mock data.
def get_characters_from_db(n):
return string.ascii_uppercase[0:n]
# A general function to have a user select N items.
def select_items(xs, n):
selected = []
print('Choices:')
for i, x in enumerate(xs):
print(i + 1, x)
print()
while len(selected) < n:
s = input('=> ')
try:
i = int(s) - 1
x = xs[i]
except Exception:
print('Invalid entry')
continue
if x in selected:
print('Already selected')
else:
selected.append(x)
print()
return selected
choose_characters()
关于python - python 通过两个函数维护列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56093292/