如果第二个列表中的元素已经在第一个列表中,在将第一个列表用小写表示之后,这段代码应该警告我。
current_users = ['id_1','id_2','id_3', 'ID_4', 'id_5']
current_users_case = [current_user_case.lower() for current_user_case in current_users]
new_users = ['id_5','id_4','id_7', 'id_8', 'id_9']
for new_user in new_users:
if new_user == current_user_case:
print("Sorry, ID already taken")
else:
print("ID available")
我得到这个错误信息:
Traceback (most recent call last):
File "main.py", line 2, in <module>
from c5n9ss import *
File "/home/runner/C5py/c5n9ss.py", line 11, in <module>
if new_user == current_user_case:
NameError: name 'current_user_case' is not defined
但是如果我在Python shell中测试前两行,我得到了正确的降低列表。
我不明白我得到的错误。
你的主意很好。只需做2个改动:
- 将
current_user_case:
更改为current_users_case:
(注意变量名中是users而不是user) - 将
if new_user == current_user_case:
更改为if new_user in current_users_case:
current_users = ['id_1','id_2','id_3', 'ID_4', 'id_5']
current_users_case = [current_user_case.lower() for current_user_case in current_users]
new_users = ['id_5','id_4','id_7', 'id_8', 'id_9']
for new_user in new_users:
if new_user in current_users_case:
print("Sorry, ID already taken")
else:
print("ID available")
当new_user
为id_5时,您希望将其与current_users_case中的所有项进行比较。如果将它与列表进行比较,则不会得到匹配,因为string (id_5)不是列表。当您使用in
时,您正在检查id_5是否在列表中,然后您的代码按预期工作。