可能重复:
'has_key()'或'in'?
我有一个Python字典,如:
mydict = {'name':'abc','city':'xyz','country','def'}
Run Code Online (Sandbox Code Playgroud)
我想检查密钥是否在字典中.我很想知道从以下两个案例中哪个更为可取,为什么?
1> if mydict.has_key('name'):
2> if 'name' in mydict:
Run Code Online (Sandbox Code Playgroud) 我的问题是一般的问题,当一个中间问题可能会返回时如何链接一系列属性查找None,但是由于我遇到了试图使用Beautiful Soup的问题,我将在那个环境中问它.
Beautiful Soup解析HTML文档并返回一个对象,该对象可用于访问该文档的结构化内容.例如,如果解析的文档在变量中soup,我可以获得其标题:
title = soup.head.title.string
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果文档没有标题,则soup.head.title返回None并且后续string查找会引发异常.我可以打破链条:
x = soup.head
x = x.title if x else None
title = x.string if x else None
Run Code Online (Sandbox Code Playgroud)
但在我看来,这是冗长而难以阅读的.
我可以写:
title = soup.head and soup.head.title and soup.title.head.string
Run Code Online (Sandbox Code Playgroud)
但这是冗长而低效的.
如果想到的话,我认为可能的一个解决方案是创建一个nil可以返回None任何属性查找的对象(调用它).这将允许我写:
title = ((soup.head or nil).title or nil).string
Run Code Online (Sandbox Code Playgroud)
但这很难看.有没有更好的办法?
我经常从我的 Python 代码中得到未捕获的异常(错误),这些异常被描述为TypeErrors. 经过大量的实验和研究,我收集了以下示例(以及细微的变化):
TypeError: func() takes 0 positional arguments but 1 was given
TypeError: func() takes from 1 to 2 positional arguments but 3 were given
TypeError: func() got an unexpected keyword argument 'arg'
TypeError: func() missing 1 required positional argument: 'arg'
TypeError: func() missing 1 required keyword-only argument: 'arg'
TypeError: func() got multiple values for argument 'arg'
TypeError: MyClass() takes no arguments
TypeError: unsupported operand type(s) for +: 'int' and 'str'
TypeError: can only concatenate str …Run Code Online (Sandbox Code Playgroud) do_something.n每次调用函数时,函数属性都会递增.
让我感到困扰的是我在函数do_something.n=0 之外声明了属性.
我回答了使用queue.PriorityQueue的问题,不关心使用"函数属性"进行比较以提供与PriorityQueue一起使用的独特计数器 - MartijnPieters有一个更好的解决方案)
MCVE:
def do_something():
do_something.n += 1
return do_something.n
# need to declare do_something.n before usign it, else
# AttributeError: 'function' object has no attribute 'n'
# on first call of do_something() occures
do_something.n = 0
for _ in range(10):
print(do_something()) # prints 1 to 10
Run Code Online (Sandbox Code Playgroud)
还有什么其他方法来定义函数"内部"的属性,以便在AttributeError: 'function' object has no attribute 'n'忘记它时避免使用它?
从评论中编辑了很多其他方式:
在Python(3.2)中实现类型安全字典的好方法是什么 - 一个只允许将特定类型的对象添加到自身的字典?
我自己有一个简单的解决方案:使用'addItem'方法在字典周围构建一个包装类,在添加对象之前执行类型检查断言.想看看有人有更好的东西.