如何使列表比较不区分大小写?
How do I make a list comparison be case insensitive?
current_ids = ['mason' , 'chase' , 'erin' , 'guillermo' , 'george']
new_ids = ['sara' , 'gregory' , 'ChaSe' , 'josh' , 'Erin']
for new in new_ids:
if new.lower() in current_ids:
print("This ID is already taken. Choose another one.")
else:
print("You aight man this ID is gucci")
我试图做到这一点,以便循环检查新 ID 是否已被使用,如果已被使用,则打印出该 ID 已被使用。问题是 "Erin" 和 "erin" 根据 python 是不一样的。我想知道我需要添加什么才能使两个列表处于同一情况。例如 curent_ids 和 new_ids 都是小写。
您给出的示例似乎有效,但我假设 current_ids
可能混合了 upper/lower 个案例。
你可以做的是使用列表理解将 current_ids 中的每个字符串转换为小写:
current_ids = [i.lower() for i in current_ids]
这会创建一个新列表,其中每个单词都 current_ids
全部小写。
然后,您可以像现在一样进行比较(if new.lower() in current_ids
)
current_ids = ['mason' , 'chase' , 'erin' , 'guillermo' , 'george']
new_ids = ['sara' , 'gregory' , 'ChaSe' , 'josh' , 'Erin']
for new in new_ids:
if new.lower() in current_ids:
print("This ID is already taken. Choose another one.")
else:
print("You aight man this ID is gucci")
我试图做到这一点,以便循环检查新 ID 是否已被使用,如果已被使用,则打印出该 ID 已被使用。问题是 "Erin" 和 "erin" 根据 python 是不一样的。我想知道我需要添加什么才能使两个列表处于同一情况。例如 curent_ids 和 new_ids 都是小写。
您给出的示例似乎有效,但我假设 current_ids
可能混合了 upper/lower 个案例。
你可以做的是使用列表理解将 current_ids 中的每个字符串转换为小写:
current_ids = [i.lower() for i in current_ids]
这会创建一个新列表,其中每个单词都 current_ids
全部小写。
然后,您可以像现在一样进行比较(if new.lower() in current_ids
)