如何检查一个列表的元素是否是一个列表(在 Python 中) ?

如果我们有以下列表:

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

如果我需要找出列表中的元素本身是否是列表,我可以用什么来替换下面代码中的 有效名单

for e in list:
if e == aValidList:
return True

有什么特殊的进口产品可以使用吗?有没有检查变量/元素是否是列表的最佳方法?

142993 次浏览

使用 isinstance:

if isinstance(e, list):

如果你想检查一个对象是一个列表还是一个元组,传递几个类到 isinstance:

if isinstance(e, (list, tuple)):

你要寻找的表达方式可能是:

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

测试:

>>> 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
>>>
  1. 计算出你希望这些项目具有的 list的特定属性。它们需要可转位吗?切片?他们需要 .append()方法吗?

  2. 查找 collections模块中描述特定类型的抽象基类。

  3. 使用 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.

也许,更直观的方式是这样的

if type(e) is list:
print('Found a list element inside the list')

你可以简单地写:

for item,i in zip(your_list, range(len(your_list)):


if type(item) == list:
print(f"{item} at index {i} is a list")