繁体   English   中英

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

[英]How to check if a list exists in Python

查看python中是否存在列表或dict的最简单方法是什么?

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

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

谢谢,

您可以使用try / except块:

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

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

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

对于列表:

if a_list:
    print "I'm not here"

同样适用于dicts:

if a_dict:
    print "I'm not here"

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

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

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

例子:

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

或者用这个:

mylist in locals().values()

简单控制台测试:

>>> 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

检查(1)变量存在 ,(2)检查它是否为列表

try:
    if type(myList) is list:
        print "myList is list"
    else:
        print "myList is not a list"
except:
    print "myList not exist"
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

暂无
暂无

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

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