How to check if an element of a list is a list (in Python)?

前端 未结 5 929
别跟我提以往
别跟我提以往 2020-12-25 09:41

If we have the following list:

list = [\'UMM\', \'Uma\', [\'Ulaster\',\'Ulter\']]

If I need to find out if an element in the list is itself

相关标签:
5条回答
  • 2020-12-25 09:51

    Expression you are looking for may be:

    ...
    return any( isinstance(e, list) for e in my_list )
    

    Testing:

    >>> my_list = [1,2]
    >>> any( isinstance(e, list) for e in my_list )
    False
    >>> my_list = [1,2, [3,4,5]]
    >>> any( isinstance(e, list) for e in my_list )
    True
    >>> 
    
    0 讨论(0)
  • 2020-12-25 09:53

    you can simply write:

    for item,i in zip(your_list, range(len(your_list)):
    
        if type(item) == list:
            print(f"{item} at index {i} is a list")
    
    0 讨论(0)
  • 2020-12-25 09:58

    Use isinstance:

    if isinstance(e, list):
    

    If you want to check that an object is a list or a tuple, pass several classes to isinstance:

    if isinstance(e, (list, tuple)):
    
    0 讨论(0)
  • 2020-12-25 10:00

    Probably, more intuitive way would be like this

    if type(e) is list:
        print('Found a list element inside the list') 
    
    0 讨论(0)
  • 2020-12-25 10:17
    1. Work out what specific properties of a list you want the items to have. Do they need to be indexable? Sliceable? Do they need an .append() method?

    2. Look up the abstract base class which describes that particular type in the collections module.

    3. Use isinstance:

      isinstance(x, collections.MutableSequence)
      

    You might ask "why not just use type(x) == list?" You shouldn't do that, because then you won't support things that look like lists. And part of the Python mentality is duck typing:

    I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck

    In other words, you shouldn't require that the objects are lists, just that they have the methods you will need. The collections module provides a bunch of abstract base classes, which are a bit like Java interfaces. Any type that is an instance of collections.Sequence, for example, will support indexing.

    0 讨论(0)
提交回复
热议问题