Skip to main content
 首页 » 编程设计

python之有人可以为我解释这段代码吗

2025年05月04日11bonelee

谁能用简单的术语为我解释这段代码。

prompts = ("Enter Strength Attribute, between 1 and 50: ", "Enter Skill Attribute, between 1 and 50: ") # I already now this so no need to explain it  
 
answers = [int(input(p)) for p in prompts] 
if not all(0 < a <=50 for a in answers): 
    # other code here 

它是发电机吗?

它是如何工作的?

提前感谢您的回答。

请您参考如下方法:

你有一个列表理解和一个​​生成器表达式。

列表理解是:

[int(input(p)) for p in prompts] 

并根据提示列表生成整数列表,要求用户输入一系列数值。

也可以表示为:

answers = [] 
for p in prompts: 
    result = int(input(p)) 
    answers.append(result) 

接下来是:

(0 < a <=50 for a in answers) 

这是生成器表达式。它测试每个数字是否是 0(不含)和 50(含)之间的值。

all() function将在生成器表达式中一次循环一个结果,并在其中一个结果为 False 时返回 False,或在返回 True 时返回 True耗尽了生成器结果,没有找到 False 值。

您可以将 if all(...) 测试替换为:

result = True 
for a in answers: 
    if not 0 < a <= 50: 
        result = False 
        break 
 
if result: 

这样会达到同样的效果;一个接一个地遍历 answers,但如果任何测试为 False(不是大于 0 且小于或等于 50 的数字),则尽早停止循环。