我在R中遇到了一个带有该sapply()功能的奇怪行为.该函数应该返回一个向量,但在给它一个空向量的特殊情况下,它返回一个列表.
使用向量纠正行为:
a = c("A", "B", "C")
a[a == "B"] # Returns "B"
a[sapply(a, function(x) {x == "B"})] # Returns "B"
Run Code Online (Sandbox Code Playgroud)
使用NULL值更正行为:
a = NULL
a[a == "B"] # Returns NULL
a[sapply(a, function(x) {x == "B"})] # Returns NULL
Run Code Online (Sandbox Code Playgroud)
使用空向量的奇怪行为:
a = vector()
a[a == "B"] # Returns NULL
a[sapply(a, function(x) {x == "B"})] # Erreur : type 'list' d'indice incorrect
Run Code Online (Sandbox Code Playgroud)
与此语句相同的错误消息:
a[list()] # Erreur dans a[list()] : type 'list' d'indice incorrect
Run Code Online (Sandbox Code Playgroud)
为什么?这是一个错误吗?
由于这种奇怪的行为,我使用unlist(lapply()).
这是一个有点奇怪的 Python 问题。
考虑以下 Python 代码:
def controlled_exec(code):
x = 0
def increment_x():
nonlocal x
x += 1
globals = {"__builtins__": {}} # remove every global (including all python builtins)
locals = {"increment_x": increment_x} # expose only the increment function
exec(code, globals, locals)
return x
Run Code Online (Sandbox Code Playgroud)
我希望这个函数能够提供一个受控代码 API,它可以简单地计算调用次数increment_x()。我尝试了一下,得到了正确的行为。
# returns 2
controlled_exec("""\
increment_x()
increment_x()
""")
Run Code Online (Sandbox Code Playgroud)
我认为这种做法并不安全,但出于好奇我想知道。我可以x通过执行代码来设置任意值(比如负数)吗controlled_exec(...)?我该怎么做呢?