简体   繁体   English

我应该用什么代替isinstance()

[英]What should I use instead of isinstance()

I have to parse some object that is composed of lists. 我必须解析一些由列表组成的对象。 But it can have list within list within list : obj=[[smth1],[[smth2],[smth3]]] each smthX can be a list aswell. 但是它可以在list内的list内有list: obj=[[smth1],[[smth2],[smth3]]]每个smthX也可以是一个列表。

I'm looking for a value that I know is in a "second layer list". 我正在寻找一个我知道的“第二层列表”中的值。 In my example, it could be in [[smth2],[smth3]] 在我的示例中,它可能在[[smth2],[smth3]]

What i'm doing right now is iterarating on my object, and testing if what i'm iterating on is a list awell. 我现在正在做的事情是迭代我的对象,并测试我正在迭代的对象是否正确。 if it is, I look for my value. 如果是这样,我会寻找自己的价值。

  for list in obj :
    if isinstance(list, obj) :
      for souslist in list :
        I LOOK FOR MY VALUE

But I'm reading everywhere ( http://canonical.org/~kragen/isinstance/ a lot of stackoverflow thread) that the use of isinstance() is only for special occasion (and my use doesn't look like a special occasion) 但是我到处都在读( http://canonical.org/~kragen/isinstance/很多stackoverflow线程), isinstance()的使用仅用于特殊场合(而我的使用看起来并不特殊) )

Before using isinstance() I was testing what list[0] returned me in a try/except but it felt even wronger. 在使用isinstance()之前,我曾尝试在try / except中测试list [0]返回了我什么,但感觉甚至更糟。 Any alternate way to achieve this in a clean way ? 还有其他方法可以以干净的方式实现这一目标吗? (I don't have any power over the format of my obj I have to work on it) (我无法处理我要处理的obj格式)

If you are looking for sub-lists with two item (which are lists) first off you need to check the length (if you are sure that all the items are list) then check if all the items in sub-list are list using isinstance() 如果您要先查找包含两个项目(列表)的子列表,则需要检查长度(如果您确定所有项目都是列表),然后使用isinstance()子列表中的所有项目是否都是列表isinstance()

for sub in obj:
    if len(sub) == 2 and all(isinstance(i, list) for i in sub): # you can add " and isinstance(sub, list)" if you are not sure about the type of sub 
        look_val(sub)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM