将当前用户名与新用户名进行比较,并检查没有不区分大小写的重复项(Python3)

时间:2017-12-28 18:48:35

标签: python-3.6

目标是将当前用户列表与当前用户列表进行比较,并检查是否没有重复的名称。如果有“John”,则不应接受“JOHN”,因此它应该不区分大小写。

到目前为止,这是我的工作,但是假设current_users已经是小写的。

current_users = ['samantha', 'albert', 'amanda', 'dick', 'becky', 'alfonso']

new_users = ['AMANDA', 'juan', 'albert', 'alexandra', 'sara', 'raheem']

for new_user in new_users:
    if new_user.lower() in current_users:
        print("Sorry! This username is taken!")
    else:
        print("You are welcome to use this name!")

我的问题是:将current_users中的所有元素转换为小写的最简洁方法是什么,而不必重写整个列表?

谢谢!

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

current_users = ['samantha', 'albert', 'amanda', 'dick', 'becky', 'alfonso']

new_users = ['AMANDA', 'juan', 'albert', 'alexandra', 'sara', 'raheem']

val = {True:'Sorry! This username is taken!',
       False:'You are welcome to use this name!'}

arr = [val[True] if new_user.lower() in current_users 
       else val[False] for new_user in new_users ]

print '\n'.join(arr)

输出:

Sorry! This username is taken!
You are welcome to use this name!
Sorry! This username is taken!
You are welcome to use this name!
You are welcome to use this name!
You are welcome to use this name!

使用列表理解和字典可能很有用。

相关问题