开发者

Python: check if value is in a list no matter the CaSE

开发者 https://www.devze.com 2023-02-17 20:31 出处:网络
I want to check if a va开发者_JAVA技巧lue is in a list, no matter what the case of the letters are, and I need to do it efficiently.

I want to check if a va开发者_JAVA技巧lue is in a list, no matter what the case of the letters are, and I need to do it efficiently.

This is what I have:

if val in list:

But I want it to ignore case


check = "asdf"
checkLower = check.lower()

print any(checkLower == val.lower() for val in ["qwert", "AsDf"])

# prints true

Using the any() function. This method is nice because you aren't recreating the list to have lowercase, it is iterating over the list, so once it finds a true value, it stops iterating and returns.

Demo : http://codepad.org/dH5DSGLP


If you know that your values are all of type str or unicode, you can try this:

if val in map(str.lower, list):
...Or:
if val in map(unicode.lower, list):


If you really have just a list of the values, the best you can do is something like

if val.lower() in [x.lower() for x in list]: ...

but it would probably be better to maintain, say, a set or dict whose keys are lowercase versions of the values in the list; that way you won't need to keep iterating over (potentially) the whole list.

Incidentally, using list as a variable name is poor style, because list is also the name of one of Python's built-in types. You're liable to find yourself trying to call the list builtin function (which turns things into lists) and getting confused because your list variable isn't callable. Or, conversely, trying to use your list variable somewhere where it happens to be out of scope and getting confused because you can't index into the list builtin.


You can lower the values and check them:

>>> val
'CaSe'
>>> l
['caSe', 'bar']
>>> val in l
False
>>> val.lower() in (i.lower() for i in l)
True


items = ['asdf', 'Asdf', 'asdF', 'asjdflk', 'asjdklflf']
itemset = set(i.lower() for i in items)

val = 'ASDF'
if val.lower() in itemset:  # O(1)
    print('wherever you go, there you are')
0

精彩评论

暂无评论...
验证码 换一张
取 消