I was just messing around in the Python interpreter and I came across some unexpected behavior.
>>> bools = (True, True, True, False)
>>> all(bools)
False
>>> any(bools)
True
Run Code Online (Sandbox Code Playgroud)
Ok, so far nothing out of the ordinary...
>>> bools = (b for b in (True, True, True, False))
>>> all(bools)
False
>>> any(bools)
False
Run Code Online (Sandbox Code Playgroud)
Here's where things start getting spooky. I figure this happens because the all
function iterates over the generator expression, calling its __next__
method and using up …
我正在使用漂亮的汤,正在尝试获取属性等于某个字符串的页面上的第一个标签。
例如:
<a href="url" title="export"></a>
Run Code Online (Sandbox Code Playgroud)
我一直想做的就是获取标题为“ export”的第一个的href。
soup.select("a[title='export']")
那么最终我会找到所有满足此要求的标签,而不仅仅是第一个。如果我使用find("a", {"title":"export"})
的条件被设置为标题应该等于“ export”,那么它将获取标签中的实际项目,而不是href。
如果我.get("href")
在致电后写信find()
,我将无回。
我一直在寻找文档和堆栈溢出来寻找答案,但尚未找到答案。有人知道解决方案吗?谢谢!
我(尝试)globals()
在我的程序中使用迭代所有全局变量.这就是我的方式:
for k, v in globals().iteritems():
function(k, v)
Run Code Online (Sandbox Code Playgroud)
当然,在这样做的过程中,我只创建了2个全局变量,k
并且v
.所以我得到了这个例外:
RuntimeError: dictionary changed size during iteration
Run Code Online (Sandbox Code Playgroud)
而且,以下是我解决问题的各种尝试失败:
# Attempt 1:
g = globals()
for k, v in globals().iteritems():
function(k, v)
# Attempt 2 (this one seems to work, but on closer inspection it duplicates
#the last item in the dictionary, because another reference is created to it):
k = v = None
for k, v in globals().iteritems():
function(k, v)
Run Code Online (Sandbox Code Playgroud)
我看过像这样的帖子处理同样的异常.这是不同的,因为无法为每个字典条目分配变量而不为其创建变量名称...这样做会引发错误.
这就是我的意思:
>>> class Foo:
pass
>>> foo = Foo()
>>> setattr(foo, "@%#$%", 10)
>>> foo.@%#$%
SyntaxError: invalid syntax
>>> getattr(foo, "@%#$%")
10
>>> foo.__dict__
{'@%#$%': 10}
Run Code Online (Sandbox Code Playgroud)
我查了一下,它在 python 2 的问题跟踪器上出现了两次:
https://bugs.python.org/issue14029
https://bugs.python.org/issue25205
一次是 Python 3:
https://bugs.python.org/issue35105
他们坚持认为这不是错误。然而,这种行为显然不是故意的。它没有记录在任何版本中。对此有何解释?这似乎是很容易被忽略的东西,但这感觉就像把它扫到地毯下一样。那么,setattr
的行为背后是否有任何原因,或者它只是 python 的一种良性特质?