我该如何解决这个问题:AttributeError:'list'对象在py3中没有属性'lower'?

时间:2018-03-29 20:54:27

标签: python-3.x

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")

我需要知道如何对此列表不区分大小写?

2 个答案:

答案 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")