current_users = ['mohammad', 'shervin' , 'ali', 'oskol' , 'pro_gamer']
new_users = ['ali', 'ahmad', 'shervin', 'lara', 'helena']
current_users.lower()
new_users.lower()
for new_user in new_users:
if new_user in current_users:
print(new_user + " You must change your user name.")
else:
print("user name is available")
我需要知道如何对此列表不区分大小写?
答案 0 :(得分:1)
您需要将该方法应用于列表中的各个字符串,而不是列表本身。
current_users = [user.lower() for user in current_users]
<强>更新强>
另一种方法是使用可以比你自己的循环更快地计算出包含的集合:
current_users = ['mohammad', 'shervin' , 'ali', 'oskol' , 'pro_gamer']
new_users = ['ali', 'ahmad', 'shervin', 'lara', 'helena']
# normalize and convert to sets
current_users = set(user.lower() for user in current_users)
new_users = set(user.lower() for user in new_users)
# use sets to make decisions
conflicts = current_users & new_users
print("users {} already exist".format(', '.join(conflicts)))
uniques = new_users - current_users
print("users {} are available".format(', '.join(uniques)))
答案 1 :(得分:0)
.lower()
只能应用于字符串。
试试这个:
current_users = ['mohammad', 'shervin', 'ali', 'oskol', 'pro_gamer']
new_users = ['ali', 'ahmad', 'shervin', 'lara', 'helena']
current_users = [user.lower() for user in current_users]
for new_user in new_users:
if new_user in current_users:
print(new_user + " You must change your user name.")
else :
print("user name is available")