是否可以在Python中为同一行分配值并增加指定值?
像这样的东西:
x = 1
a = x
b = (x += 1)
c = (x += 1)
print a
print b
print c
>>> 1
>>> 2
>>> 3
Run Code Online (Sandbox Code Playgroud)
编辑: 我需要在我创建Excel工作表的上下文中:
col = row = 1
ws.cell(row=row, column=col).value = "A cell value"
ws.cell(row=row, column=(col += 1)).value = "Another cell value"
ws.cell(row=row, column=(col += 1)).value = "Another cell value"
Run Code Online (Sandbox Code Playgroud)
编辑2:解决方案: 这是不可能的,但我创建了一个简单的修复:
col = row = 1
def increment_one():
global col
col += 1
return col
ws.cell(row=row, column=col).value = "A cell value"
ws.cell(row=row, column=increment_one()).value = "Another cell value"
ws.cell(row=row, column=increment_one()).value = "Another cell value"
Run Code Online (Sandbox Code Playgroud)
不,这在Python中是不可能的.
作业(或增强作业)是声明,因此可能不会出现在另一作业的右侧.您只能将表达式分配给变量.
其原因很可能是避免因支持这种情况的其他语言容易引起的副作用造成的混淆.
但是,正常分配确实支持多个目标,因此您可以将同一表达式分配给多个变量.这当然仍然只允许你在右侧有一个表达式(仍然没有声明).在你的情况下,既然你想要b并x最终得到相同的值,你可以像这样写:
b = x = x + 1
c = x = x + 1
Run Code Online (Sandbox Code Playgroud)
请注意,由于您正在进行操作x = x + 1,因此不再使用扩充分配,因此对某些类型可能会产生不同的效果(尽管不是整数).
从 Python 3.8 开始,您可以使用PEP-572中引入的walrus 运算符。该运算符创建一个赋值表达式。因此,您可以为变量分配新值,同时返回新分配的值:
>>> print(f"{(x := 1)}")
1
>>> x
1
>>> print(f"{(x := x+1)}")
2
>>> x
2
>>> b = (x := x+1)
>>> b, x
(3, 3)
Run Code Online (Sandbox Code Playgroud)
根据您的问题,这将起作用:
col = row = 1
ws.cell(row=row, column=col).value = "A cell value"
ws.cell(row=row, column=(col := col+1)).value = "Another cell value"
ws.cell(row=row, column=(col := col+1)).value = "Another cell value"
Run Code Online (Sandbox Code Playgroud)