我的程序有问题,它什么也不返回

2024-10-01 05:03:42 发布

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

我正试图编写一个程序,从“tab”列表中提取5个随机字符,并将它们附加到其他列表(t1)中。下一步是比较t1列表和“赢”列表(此列表包含幸运字符)。若t1等于WIN,程序应该返回幸运字符(t1)和所有尝试的总和(p),但它当然不起作用。你能帮我吗

tab=['a','e','x','t','b','3','536','2','5','6','79','5634','2','234','0']
win=['a','x','3','79','b']
t1=[]
active=True
p=0
while active:
    for i in range(5):
        wygrana=choice(tab)
        t1.append(wygrana)
    win.sort()
    t1.sort()
    if win==t1:
        p+=1
        print(f"You WON!! You needed {p} attempts, and your lucky characters are {t1}")
        active=False
    else:
        p+=1

Tags: 程序youtrue列表sort字符tabwin
2条回答

您永远不会清除t1列表。您可以按如下方式简化一切并避免此问题。如果选项在win中,则它仅通过附加到列表理解来工作。如果最终列表的长度与win相同,那么它必须具有所有正确的元素

您不需要使用此方法sort任何东西,并且您的一组变量变得不必要

from random import choice

tab=['a','e','x','t','b','3','536','2','5','6','79','5634','2','234','0']
win=['a','x','3','79','b']

p=1
while len([i for i in range(5) if choice(tab) in win]) < 5:
    p+=1
    
print(f"You WON!! You needed {p} attempts, and your lucky characters are \"{' '.join(win)}\"")

如果你想让它更有活力,你可以这样做

from random import choice, randint

tab=[chr(i+(randint(0, 1)*32)) for i in range(65, 91)]
win=[choice(tab) for _ in range(5)]

p=1
while len([_ for _ in range(5) if choice(tab) in win]) < 5:
    p+=1
    
print(f"You WON!! You needed {p} attempts, and your lucky characters are \"{' '.join(win)}\"")

根据每次迭代后的User:jasonharper清除t1,因为您使用的是append方法,该方法将在单次迭代后继续在后面添加元素,其大小超过5,这使得条件始终False
在代码中进行以下更改:

...
while active:
    for i in range(5):
...

...
while active:
    t1 = []
    for i in range(5):
...

方法2

使用以下方法创建t1-list,其中自动重新创建每个迭代t1

...
while active:
    t1 = [choice(tab) for _ in range(5)]
    win.sort()
    t1.sort()
...

相关问题 更多 >