Check element exists in array

后端 未结 6 875
说谎
说谎 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 08:56

    EAFP vs. LBYL

    I understand your dilemma, but Python is not PHP and coding style known as Easier to Ask for Forgiveness than for Permission (or EAFP in short) is a common coding style in Python.

    See the source (from documentation):

    EAFP - Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

    So, basically, using try-catch statements here is not a last resort; it is a common practice.

    "Arrays" in Python

    PHP has associative and non-associative arrays, Python has lists, tuples and dictionaries. Lists are similar to non-associative PHP arrays, dictionaries are similar to associative PHP arrays.

    If you want to check whether "key" exists in "array", you must first tell what type in Python it is, because they throw different errors when the "key" is not present:

    >>> l = [1,2,3]
    >>> l[4]
    
    Traceback (most recent call last):
      File "", line 1, in 
        l[4]
    IndexError: list index out of range
    >>> d = {0: '1', 1: '2', 2: '3'}
    >>> d[4]
    
    Traceback (most recent call last):
      File "", line 1, in 
        d[4]
    KeyError: 4
    

    And if you use EAFP coding style, you should just catch these errors appropriately.

    LBYL coding style - checking indexes' existence

    If you insist on using LBYL approach, these are solutions for you:

    • for lists just check the length and if possible_index < len(your_list), then your_list[possible_index] exists, otherwise it doesn't:

      >>> your_list = [0, 1, 2, 3]
      >>> 1 < len(your_list) # index exist
      True
      >>> 4 < len(your_list) # index does not exist
      False
      
    • for dictionaries you can use in keyword and if possible_index in your_dict, then your_dict[possible_index] exists, otherwise it doesn't:

      >>> your_dict = {0: 0, 1: 1, 2: 2, 3: 3}
      >>> 1 in your_dict # index exists
      True
      >>> 4 in your_dict # index does not exist
      False
      

    Did it help?

提交回复
热议问题