检查 python 中是否存在列表或字典的最简单方法是什么?
我正在使用以下内容,但这不起作用:
if len(list) == 0:
print "Im not here"
谢谢,
检查 python 中是否存在列表或字典的最简单方法是什么?
我正在使用以下内容,但这不起作用:
if len(list) == 0:
print "Im not here"
谢谢,
您可以使用 try/except 块:
try:
#work with list
except NameError:
print "list isn't defined"
对于列表:
if a_list:
print "I'm not here"
dicts 也是如此:
if a_dict:
print "I'm not here"
当您尝试引用不存在的变量时,解释器会引发NameError
. 但是,依赖代码中变量的存在是不安全的(您最好将其初始化为 None 或其他东西)。有时我用这个:
try:
mylist
print "I'm here"
except NameError:
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! :)"
如果我们需要避免in 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