+=
python中的运算符似乎在列表上意外运行.谁能告诉我这里发生了什么?
class foo:
bar = []
def __init__(self,x):
self.bar += [x]
class foo2:
bar = []
def __init__(self,x):
self.bar = self.bar + [x]
f = foo(1)
g = foo(2)
print f.bar
print g.bar
f.bar += [3]
print f.bar
print g.bar
f.bar = f.bar + [4]
print f.bar
print g.bar
f = foo2(1)
g = foo2(2)
print f.bar
print g.bar
Run Code Online (Sandbox Code Playgroud)
OUTPUT
[1, 2]
[1, 2]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3]
[1]
[2] …
Run Code Online (Sandbox Code Playgroud) 是否有与以下功能等效的标准库/ numpy:
def augmented_assignment_sum(iterable, start=0):
for n in iterable:
start += n
return start
Run Code Online (Sandbox Code Playgroud)
?
虽然sum(ITERABLE)
非常优雅,但它使用+
operator代替+=
,如果出现np.ndarray
对象,这可能会影响性能。
我已经测试过,我的功能可能和它一样快sum()
(而使用它的等效+
速度要慢得多)。由于它是纯Python函数,因此我认为它的性能仍然受到限制,因此我正在寻找一些替代方法:
In [49]: ARRAYS = [np.random.random((1000000)) for _ in range(100)]
In [50]: def not_augmented_assignment_sum(iterable, start=0):
...: for n in iterable:
...: start = start + n
...: return start
...:
In [51]: %timeit not_augmented_assignment_sum(ARRAYS)
63.6 ms ± 8.88 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
In …
Run Code Online (Sandbox Code Playgroud) python performance numpy standard-library augmented-assignment
Python是否具有与其布尔运算符对应的扩充赋值语句?
例如,我可以这样写:
x = x + 1
Run Code Online (Sandbox Code Playgroud)
或这个:
x += 1
Run Code Online (Sandbox Code Playgroud)
有什么我可以写的代替这个:
x = x and y
Run Code Online (Sandbox Code Playgroud)
为避免两次写"x"?
请注意,我知道使用&=的语句,但我正在寻找一个当y是任何类型时都能工作的语句,而不仅仅是当y是布尔值时.
在缩短我的代码的同时,我将一些变量声明减少到一行 -
##For example- going from-
Var1 =15
Var2 = 26
Var3 = 922
##To-
Var1, Var2, Var3 = 15, 26, 922
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试对此代码做同样的事情时 -
User_Input += Master_Key[Input_ref]
Key += Master_Key[Key_ref]
Key2 += Master_Key[Key_2_Ref]
##Which looks like-
User_Input, Key, Key2 += Master_Key[Input_Ref], Master_Key[Key_Ref], Master_Key[Key_2_Ref]
Run Code Online (Sandbox Code Playgroud)
这会引发错误
SyntaxError: illegal expression for augmented assignment
Run Code Online (Sandbox Code Playgroud)
我已经阅读了相关的Python文档,但我仍然找不到缩短这一特定代码的方法.
我有两个类,一个是"就地操作符"覆盖(比如说+=
),另一个是通过a公开第一个实例@property
.(注意:从我的实际代码到再现问题的最小代码,这大大简化了.)
class MyValue(object):
def __init__(self, value):
self.value = value
def __iadd__(self, other):
self.value += other
return self
def __repr__(self):
return str(self.value)
class MyOwner(object):
def __init__(self):
self._what = MyValue(40)
@property
def what(self):
return self._what
Run Code Online (Sandbox Code Playgroud)
现在,当我尝试在公开的属性上使用该运算符时:
>>> owner = MyOwner()
>>> owner.what += 2
AttributeError: can't set attribute
Run Code Online (Sandbox Code Playgroud)
从我发现这是预期的,因为它试图设置属性owner
. 有没有办法防止将属性设置为新对象,同时仍然允许我(就地)修改它后面的对象,或者这只是语言的怪癖?
(另请参阅此问题,但我试图采用其他方式,最好不要回到旧式类,因为最终我希望它能与Python 3一起使用.)
与此同时,我用一种方法做了同样的事情.
class MyValue(object):
# ...
def add(self, other):
self.value += other
>>> …
Run Code Online (Sandbox Code Playgroud) python properties new-style-class python-2.7 augmented-assignment
看来这个问题只回答了Java,但我想知道它是如何在Python中运行的.这些都一样吗?
a += b / 2
Run Code Online (Sandbox Code Playgroud)
和
a += (b / 2)
Run Code Online (Sandbox Code Playgroud) 我想继承一个不可变类型或实现我自己的类型,其行为类似于int
以下控制台会话中显示的:
>>> i=42
>>> id(i)
10021708
>>> i.__iadd__(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute '__iadd__'
>>> i += 1
>>> i
43
>>> id(i)
10021696
Run Code Online (Sandbox Code Playgroud)
毫不奇怪,int
对象没有__iadd__()
方法,但是应用于+=
一个不会导致错误,相反它显然会创建一个新的int
,并且不知何故神奇地将它重新分配给扩充赋值语句中给出的名称.
是否可以创建一个用户定义的类或内置不可变类的子类,如果是这样,如何?
今天我试图找到一个方法,在python中对字符串进行一些处理.一些比我说的高级程序员不使用+=
但使用''.join()
我也可以在例如http://wiki.python.org/moin/PythonSpeed/#Use_the_best_algorithms_and_fastest_tools中阅读.但是我自己测试了这个并且发现了一些奇怪的结果(这不是我想要再猜测它们但是我想要站立).想法是,如果有一个"This is \"an example text\"
包含空格的字符串"字符串应该被转换为Thisis"an example text"containingspaces
空格被删除,但只在引号之外.
我测量了我的算法的两个不同版本的性能,使用了''.join(list)
一个和一个+=
import time
#uses '+=' operator
def strip_spaces ( s ):
ret_val = ""
quote_found = False
for i in s:
if i == '"':
quote_found = not quote_found
if i == ' ' and quote_found == True:
ret_val += i
if i != ' ':
ret_val += i
return ret_val
#uses "".join ()
def strip_spaces_join ( s ):
#ret_val …
Run Code Online (Sandbox Code Playgroud) 我定义了两个函数作为最小的工作示例。
\nIn [2]: A = np.random.random(10_000_000)\n\nIn [3]: def f():\n ...: return A.copy() * np.pi\n ...: \n\nIn [4]: def g():\n ...: B = A.copy()\n ...: B *= np.pi\n ...: return B\n
Run Code Online (Sandbox Code Playgroud)\n它们都返回相同的结果:
\nIn [5]: assert all(f() == g())\n
Run Code Online (Sandbox Code Playgroud)\n但我希望g()
更快,因为增强赋值 (for A
) 比乘法快 4 倍多:
In [7]: %timeit B = A.copy(); B * np.pi\n82.2 ms \xc2\xb1 301 \xc2\xb5s per loop (mean \xc2\xb1 std. dev. of 7 runs, 10 loops each)\n\nIn [8]: %timeit B = …
Run Code Online (Sandbox Code Playgroud) m = 0
for i in range(1,1000):
if i % 3 == 0 or i % 5 == 0:
m += m
print m
Run Code Online (Sandbox Code Playgroud)
这给出0
了答案.答案应该是233168
.
在我的IDE中结束的行可能是个问题吗?我正在使用pycharm.
编辑:注意自己 - 休息一下.我一发布这个就找到了错字.在此之前我遇到了ide和line结尾的问题.无论如何,谢谢:)巨魔走了
我正在摆弄一行if if和for python中的语句并遇到以下问题:
我可以做类似以下的工作:
state = 1 if state == 4 else 2
Run Code Online (Sandbox Code Playgroud)
但我想在相同的上下文中使用=和+ =,如下所示:
state = 1 if state == 4 else state+=1
Run Code Online (Sandbox Code Playgroud)
我怎样才能在一行中实现这一点?
由Martijn Pieters回答.谢谢.
这是因为声明与表达.并且因为.join()不变异(是纯函数),所以需要将其赋值给变量.
问题:
这种奇怪的原因是什么?
目标:
if base == 'T':
RNA_seq += 'U'
else:
RNA_seq += base
Run Code Online (Sandbox Code Playgroud)
以下方法有效:
# += in expression1 and .join() in expression2
RNA_seq += 'U' if base == 'T' else RNA_seq.join(base)
# Edit note: RNA_seq.join(base) works because it returns `base`
# aka. RNA_seq += 'U' if base == 'T' else base
Run Code Online (Sandbox Code Playgroud)
但是以下不起作用:
# Using += on both expressions
RNA_seq += 'U' if base == 'T' else RNA_seq += base
Run Code Online (Sandbox Code Playgroud)
要么
# Using .join() for both expressions …
Run Code Online (Sandbox Code Playgroud) python ×12
performance ×3
numpy ×2
addition ×1
immutability ×1
optimization ×1
properties ×1
python-2.7 ×1
range ×1
reference ×1
variables ×1