这段代码:
a = [1, 2, 3]
print(*a, a.pop(0))
Run Code Online (Sandbox Code Playgroud)
Python 3.8 打印2 3 1(在解包之前进行pop)。
Python 3.9 打印1 2 3 1(解压后执行pop)。
是什么导致了这种变化?我在变更日志中没有找到它。
编辑:不仅在函数调用中,而且在列表显示中:
a = [1, 2, 3]
b = [*a, a.pop(0)]
print(b)
Run Code Online (Sandbox Code Playgroud)
打印[2, 3, 1]vs[1, 2, 3, 1]打印 表达式列表显示“表达式从左到右求值”(这是 Python 3.8 文档的链接),所以我希望首先发生解包表达式。
为什么set函数调用会消除欺骗,但解析集合文字却没有?
>>> x = Decimal('0')
>>> y = complex(0,0)
>>> set([0, x, y])
{0}
>>> {0, x, y}
{Decimal('0'), 0j}
Run Code Online (Sandbox Code Playgroud)
(Python 2.7.12.可能与此类似问题的根本原因相同)
假设在Python中从左到右计算函数参数是否安全?
参考说明它发生的方式,但也许有一些方法来改变这个可能会破坏我的代码的顺序.
我想要做的是为函数调用添加时间戳:
l = []
l.append(f(), time.time())
Run Code Online (Sandbox Code Playgroud)
我知道我可以按顺序评估参数:
l = []
res = f()
t = time.time()
l.append(res, t)
Run Code Online (Sandbox Code Playgroud)
但它看起来不那么优雅,所以如果我可以依赖它,我更喜欢第一种方式.
如果arr = [4,3,2,1]我想将第一个值与数组的最小值交换,如果我在python上使用它
arr[0] , arr[arr.index(min(arr))] = min(arr) , arr[0]
#or
arr[0] , arr[arr.index(min(arr))] = arr[arr.index(min(arr))] , arr[0]
Run Code Online (Sandbox Code Playgroud)
他们不工作,但如果我这样做
b = arr.index(min(arr))
#and then
arr[0] , arr[b] = arr[b] , arr[0]
Run Code Online (Sandbox Code Playgroud)
这很好用.有谁能解释为什么?
例如,在JavaScript中我们可以编写这样的程序:
var a = 1;
testFunction(++a, ++a, a);
function testFunction(x, y, z){
document.writeln("<br />x = " + x);
document.writeln("<br />y = " + y);
document.writeln("<br />z = " + z);
}
Run Code Online (Sandbox Code Playgroud)
我们会得到一个输出:
x = 2
y = 3
z = 3
Run Code Online (Sandbox Code Playgroud)
这意味着在JavaScript中从左到右真正地评估参数.在C中我们会得到输出
x = 3
y = 3
z = 3
Run Code Online (Sandbox Code Playgroud)
我想知道我们是否可以在Python中做同样的事情,或者它是不可能的,因为它是价值参考语言的传递?
我做了一个简单的程序,但我不认为这证明了什么:
x = 2
def f(x, y, z):
print(x, y, z)
f(x*2, x*2, x**2)
print(x)
Run Code Online (Sandbox Code Playgroud)
4 4 4
2
Run Code Online (Sandbox Code Playgroud)
当我调用它时,Python不会让我在函数参数中做任何新的赋值(例如f(x=4, x, x)或类似的东西).
换句话说就是
d = {}
d["key"] = len(d)
Run Code Online (Sandbox Code Playgroud)
安全的Python?
我知道这是C++中未定义的行为 ; 在计算要分配给它的值之前,程序可能会获得对元素的引用.这在Python中是类似的还是len(d)以前总是计算d.__getitem__("key")?
这是一段代码片段.
x = {}
x[1] = len(x)
print x
{1: 0}
Run Code Online (Sandbox Code Playgroud)
这个定义得很好吗?也就是说,可以x == {1: 1}呢?
因为我记得C++ '98中的等效程序(如果我们使用std::map)具有未定义的行为.使用VS编译器和G ++编译时,程序的输出是不同的.
python ×7
arguments ×1
arrays ×1
hash ×1
list ×1
python-2.7 ×1
python-2.x ×1
python-3.x ×1
set ×1