简体   繁体   English

检查对象是否为列表的pythonic方法是什么?

[英]What is the pythonic way of checking if an object is a list?

I have a function that may take in a number or a list of numbers. 我有一个函数,可以包含一个数字或一个数字列表。 Whats the most pythonic way of checking which it is? 什么是最pythonic方式检查它是什么? So far I've come up with try/except block checking if i can slice the zero item ie. 到目前为止,我已经提出了try / except块检查,如果我可以切片零项,即。 obj[0:0] OBJ [0:0]

Edit: 编辑:

I seem to have started a war of words down below by not giving enough info. 由于没有提供足够的信息,我似乎已经在下面开始了一场口水战。 For completeness let me provide more details so that I may pick and get the best answer for my situation: 为了完整性,让我提供更多细节,以便我可以挑选并获得最佳答案:

I'm running Django on Python 2.6 and I'm writing a function that may take in a Django model instance or a queryset object and perform operations on it one of which involves using the filter 'in' that requires a list (the queryset input), or alternately if it is not a list then I would use the 'get' filter (the django get filter). 我在Python 2.6上运行Django,我正在编写一个可以接受Django模型实例或查询集对象并对其执行操作的函数,其中一个函数涉及使用需要列表的过滤器'in'(查询集输入) ),或者如果它不是列表,那么我会使用'get'过滤器(django get过滤器)。

In such situations, you normally need to check for ANY iterable, not just lists -- if you're accepting lists OR numbers, rejecting (eg) a tuple would be weird. 在这种情况下,您通常需要检查任何可迭代的,而不仅仅是列表 - 如果您接受列表或数字,拒绝(例如)元组将是奇怪的。 The one kind of iterable you might want to treat as a "scalar" is a string -- in Python 2.*, this means str or unicode . 您可能想要将其视为“标量”的一种可迭代是字符串 - 在Python 2. *中,这意味着strunicode So, either: 那么,要么:

def isNonStringIterable(x):
  if isinstance(x, basestring):
    return False
  try: iter(x)
  except: return False
  else: return True

or, usually much handier: 或者,通常更方便:

def makeNonStringIterable(x):
  if isinstance(x, basestring):
    return (x,)
  try: return iter(x)
  except: return (x,)

where you just go for i in makeNonStringIterable(x): ... for i in makeNonStringIterable(x): ...去哪里for i in makeNonStringIterable(x): ...

if isinstance(your_object, list):
  print("your object is a list!")

This is more Pythonic than checking with type. 这比使用类型检查更像Pythonic。

Seems faster too: 似乎也更快:

>>> timeit('isinstance(x, list)', 'x = [1, 2, 3, 4]')
0.40161490440368652
>>> timeit('type(x) is list', 'x = [1, 2, 3, 4]')
0.46065497398376465
>>> 

You don't. 你没有。

This works only for Python >= 2.6. 这仅适用于Python> = 2.6。 If you're targeting anything below use Alex' solution . 如果您的目标是以下任何内容,请使用Alex的解决方案

Python supports something called Duck Typing . Python支持名为Duck Typing的东西。 You can look for certain functionality using the ABC classes . 您可以使用ABC类查找某些功能。

import collections
def mymethod(myvar):
    # collections.Sqeuence to check for list capabilities
    # collections.Iterable to check for iterator capabilities
    if not isinstance(myvar, collections.Iterable):
        raise TypeError()

I don't want to be a pest, BUT: Are you sure the query set/object is a good interface? 我不想成为害虫,但是:你确定查询集/对象是一个好的界面吗? Make two functions, like: 制作两个功能,例如:

def fobject(i):
   # do something

def fqueryset(q):
   for obj in q:
       fobject( obj )

Might not be the pythonic way to discern an int from a list, but seems a far better design to me. 可能不是从列表中识别int的pythonic方法,但对我来说似乎是一个更好的设计。

Reason being : Your function should be working on ducks. 原因是 :你的功能应该是鸭子。 As long as it quacks, whack it. 只要它嘎嘎叫,就打它了。 Actually picking the duck up, turning it upside down to check the markings on the belly before choosing the right club to whack it is unpythonic . 实际上是把鸭子捡起来,把它翻过来检查肚子上的标记,然后再选择合适的球杆进行打击,这是非常的 Sorry. 抱歉。 Just don't go there. 只是不要去那里。

You can use isinstance to check a variables type: 您可以使用isinstance检查变量类型:

if isinstance(param, list):
   # it is a list
   print len(list)

I think the way OP is doing, checking if it supports what he wants, is ok. 我认为OP正在做的方式,检查它是否支持他想要的东西,是可以的。

Simpler way in this scenario would be to not check for list which can be of many types depending on definition, you may check if input is number, do something on it else try to use it as list if that throws exception bail out. 在这种情况下更简单的方法是不检查列表,根据定义可以是多种类型,您可以检查输入是否为数字,在其上执行某些操作,否则尝试将其用作列表,如果它抛出异常保释。

eg you may not want iterate over list but just wanted to append something to it if it is list else add to it 例如,你可能不希望迭代列表,但只是想要添加一些东西,如果它是列表,否则添加到它

def add2(o):
    try:
        o.append(2)
    except AttributeError:
        o += 2

l=[]
n=1
s=""
add2(l)
add2(n)
add2(s) # will throw exception, let the user take care of that ;)

So bottom line is answer may vary depending on what you want to do with object 所以底线是答案可能会有所不同取决于你想用对象做什么

Just use the type method? 只需使用类型方法? Or am I misinterpreting the question 或者我是否误解了这个问题

if type(objectname) is list:
  do something
else:
  do something else :P

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

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