简体   繁体   中英

in python how comparison of two list, we can make case insensitive?

If "Maurya" is present in current_users, then "MAURYA" should not be accepted as available username.

current_users = ["amit", "ajit", "nishant", "mohit", "Maurya"]
new_users = ["deepak", "manish", "maurya", "akhil", "ajit"]

for new_user in new_users:
    if new_user in current_users:
        print(f"{new_user}, you need to enter new username!")
    else:
        print(f"{new_user}, This username is available.")
for new_user in new_users:
    for current_user in current_users:
        if new_user.lower() == current_user.lower():
            print('new user {} allready present'.format(new_user))

If you care about performance and your input is big, do a couple of things on top of the answer what solid.py has given.

  1. Convert the current users to a set
  2. Use that set in loop
current_users = ["amit", "ajit", "nishant", "mohit", "Maurya"]
current_user_set = {user.lower() for user in current_users}

new_users = ["deepak", "manish", "maurya", "akhil", "ajit"]

for new_user in [user.lower() for user in new_users]:
    if new_user in current_user_set:
        print(f"{new_user}, you need to enter new username!")
    else:
        print(f"{new_user}, This username is available.")

A more robust approach, in my opinion is to use case-folding as it'll be useful for comparing names which aren't necessarily plane Indian names. Also performance wise it happens to provide more* than str.lower() method.

Code:

current_users = ["amit", "ajit", "nishant", "mohit", "Maurya"]
new_users = ["deepak", "manish", "maurya", "akhil", "ajit"]

for new_user in new_users:
  if new_user in map(str.casefold, current_users):
    print(f"{new_user}, you need to enter new username!")
  else:
    print(f"{new_user}, This username is available.")

Output:

>>> deepak, This username is available.
>>> manish, This username is available.
>>> maurya, you need to enter new username!
>>> akhil, This username is available.
>>> ajit, you need to enter new username!

But all the other methods work like a charm: :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM