如何检查Python中是否存在列表

时间:2012-07-19 07:53:24

标签: python

检查python中是否存在列表或字典的最简单方法是什么?

我使用以下内容但这不起作用:

if len(list) == 0:
    print "Im not here"

谢谢,

8 个答案:

答案 0 :(得分:9)

您可以使用try / except块:

try:
    #work with list
except NameError:
    print "list isn't defined"

答案 1 :(得分:6)

当您尝试引用不存在的变量时,解释器会引发NameError。但是,依赖代码中存在变量并不安全(最​​好将其初始化为None或其他东西)。有时候我用过这个:

try:
    mylist
    print "I'm here"
except NameError:
    print "I'm not here"

答案 2 :(得分:5)

列表:

if a_list:
    print "I'm not here"

同样适用于dicts:

if a_dict:
    print "I'm not here"

答案 3 :(得分:4)

如果你能够命名它 - 它显然“存在” - 我认为你的意思是检查它是否“非空”......最pythonic的方法是使用if varname:。注意,这不适用于生成器/迭代器,以检查它们是否返回数据,因为结果始终为True

如果您只想使用某个索引/键,那么只需尝试使用它:

try:
    print someobj[5]
except (KeyError, IndexError) as e: # For dict, list|tuple
    print 'could not get it'

答案 4 :(得分:2)

示例:

mylist=[1,2,3]
'mylist' in locals().keys()

或者使用它:

mylist in locals().values()

答案 5 :(得分:1)

简单的控制台测试:

>>> if len(b) == 0: print "Ups!"
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined

>>> try:
...     len(b)
... except Exception as e:
...     print e
... 
name 'b' is not defined

示例显示如何检查列表是否包含元素:

alist = [1,2,3]
if alist: print "I'm here!"

Output: I'm here!

否则:

alist = []
if not alist: print "Somebody here?"

Output: Somebody here?

如果你需要检查列表/元组的存在/不存在,这可能会有所帮助:

from types import ListType, TupleType
a_list = [1,2,3,4]
a_tuple = (1,2,3,4)

# for an existing/nonexisting list
# "a_list" in globals() check if "a_list" is defined (not undefined :p)

if "a_list" in globals() and type(a_list) is ListType: 
    print "I'm a list, therefore I am an existing list! :)"

# for an existing/nonexisting tuple
if "a_tuple" in globals() and type(a_tuple) is TupleType: 
    print "I'm a tuple, therefore I am an existing tuple! :)"

如果我们需要避免在globals()中 ,我们可以使用它:

from types import ListType, TupleType
try:
    # for an existing/nonexisting list
    if type(ima_list) is ListType: 
        print "I'm a list, therefore I am an existing list! :)"

    # for an existing/nonexisting tuple
    if type(ima_tuple) is TupleType: 
        print "I'm a tuple, therefore I am an existing tuple! :)"
except Exception, e:
    print "%s" % e

Output:
    name 'ima_list' is not defined
    ---
    name 'ima_tuple' is not defined

<强>参考书目: 8.15。 types - 内置类型的名称 - Python v2.7.3文档https://docs.python.org/3/library/types.html

答案 6 :(得分:0)

检查(1)变量存在和(2)检查列表

try:
    if type(myList) is list:
        print "myList is list"
    else:
        print "myList is not a list"
except:
    print "myList not exist"

答案 7 :(得分:0)

s = set([1, 2, 3, 4])
if 3 in s:
    print("The number 3 is in the list.")
else:
    print("The number 3 is NOT in the list.")

您可以在此处找到更多相关信息:https://docs.quantifiedcode.com/python-anti-patterns/performance/using_key_in_list_to_check_if_key_is_contained_in_a_list.html