Check element exists in array

后端 未结 6 819
说谎
说谎 2021-01-30 08:23

In PHP there a function called isset() to check if something (like an array index) exists and has a value. How about Python?

I need to use this on arrays because I get \

6条回答
  •  走了就别回头了
    2021-01-30 09:04

    `e` in ['a', 'b', 'c']  # evaluates as False
    `b` in ['a', 'b', 'c']  # evaluates as True
    

    EDIT: With the clarification, new answer:

    Note that PHP arrays are vastly different from Python's, combining arrays and dicts into one confused structure. Python arrays always have indices from 0 to len(arr) - 1, so you can check whether your index is in that range. try/catch is a good way to do it pythonically, though.

    If you're asking about the hash functionality of PHP "arrays" (Python's dict), then my previous answer still kind of stands:

    `baz` in {'foo': 17, 'bar': 19}  # evaluates as False
    `foo` in {'foo': 17, 'bar': 19}  # evaluates as True
    

提交回复
热议问题