【问题标题】:How do I make a list comparison be case insensitive?如何使列表比较不区分大小写?
【发布时间】:2017-09-16 02:30:57
【问题描述】:
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 已在使用中。问题是根据python,“Erin”和“erin”是不一样的。我想知道我需要添加什么才能使两个列表处于相同的情况。例如,curent_ids 和 new_ids 都为小写。

【问题讨论】:

  • 运行此代码时会得到什么输出?我觉得很好。此外,如果current_ids 是一个集合,即current_ids = {'mason' , 'chase' , 'erin' , 'guillermo' , 'george'},效率会更高

标签: python python-3.x coding-style


【解决方案1】:

您给出的示例似乎有效,但我假设current_ids 可能混合使用大写/小写。

您可以做的是使用列表推导将 current_ids 中的每个字符串转换为小写:

current_ids = [i.lower() for i in current_ids]

这会创建一个新列表,其中包含current_ids 中的每个单词,全部小写。

然后,您可以像现在一样进行比较(if new.lower() in current_ids

【讨论】:

  • 非常感谢。我已经看过这行代码,但它总是与其他类型的代码进行比较,所以我不知道它是否适合我,你实际上让我的代码完全按照我想要的方式工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多