【发布时间】:2022-11-23 20:31:59
【问题描述】:
在 Python 中寻找安全的随机密码生成器时,我遇到了这个脚本:
# necessary imports
import secrets
import string
# define the alphabet
letters = string.ascii_letters
digits = string.digits
special_chars = string.punctuation
alphabet = letters + digits + special_chars
# fix password length
pwd_length = 12
# generate a password string
pwd = ''
for i in range(pwd_length):
pwd += ''.join(secrets.choice(alphabet))
print(pwd)
# generate password meeting constraints
while True:
pwd = ''
for i in range(pwd_length):
pwd += ''.join(secrets.choice(alphabet))
if (any(char in special_chars for char in pwd) and
sum(char in digits for char in pwd)>=2):
break
print(pwd)
来源:How to Create a Random Password Generator in Python - Geekflare 在最后的“if”语句中有一件事我不清楚,它检查生成的密码是否满足某些约束。
表达式是:
char in special_chars for char in pwd
我知道,“in”可以检查某物是否是可迭代对象的一部分,或者是从可迭代对象生成循环的“for in”语句的一部分。
但我不明白的是这两者在这里是如何相互作用的。在我看来,“char in special_chars”似乎检查“for char in pwd”中定义的第二个“char”是否是special_chars 的一部分。
但是:如何在定义“for in”中的“char”之前定义第一个“char”?我一直认为变量在定义之前无法访问。这个例子在我看来好像 Python 的行为有所不同。有人可以向我解释一下吗?
【问题讨论】:
-
它叫做list comprehension,它有自己的语法。
-
@SembeiNorimaki 在那种情况下它是生成器表达式,但想法是一样的。
标签: python for-loop in-operator