相关疑难解决方法(0)

为什么+ =在列表上出现意外行为?

+=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)

python augmented-assignment

103
推荐指数
6
解决办法
6万
查看次数

list .__ iadd__和list .__ add__的不同行为

考虑以下代码:

>>> x = y = [1, 2, 3, 4]
>>> x += [4]
>>> x
[1, 2, 3, 4, 4]
>>> y
[1, 2, 3, 4, 4]
Run Code Online (Sandbox Code Playgroud)

然后考虑这个:

>>> x = y = [1, 2, 3, 4]
>>> x = x + [4]
>>> x
[1, 2, 3, 4, 4]
>>> y
[1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

为什么这两个有区别?

(是的,我试着寻找这个).

python list

12
推荐指数
2
解决办法
4936
查看次数

将字符串添加到列表中

>>> b = []
>>> c = '1234'
>>> b += c
>>> b
['1', '2', '3', '4']
>>> 
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?这应该不行,对吗?还是我错过了一些明显的东西?

>>> b = []
>>> c = '1234'
>>> b + c
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    b + c
TypeError: can only concatenate list (not "str") to list
>>> 
Run Code Online (Sandbox Code Playgroud)

然后a += b 并不总是等同于a = a + b

python string list

8
推荐指数
3
解决办法
7040
查看次数

Python:list.extend和list .__ iadd__之间的区别

我认为list.extend列表中的"+ ="基本上做同样的事情 - 扩展列表而不创建新列表.

我希望下面的代码可以打印,[42, 43, 44, 45, 46]但我得到了UnboundLocalError: local variable 'x' referenced before assignment

为什么我收到此错误?区别在哪里?

def f():
    x.extend([43, 44])
def g():
    x += ([45, 46])
x = [42]
f()
g()
print x
Run Code Online (Sandbox Code Playgroud)

我在python2.7.3和python3.4.0中尝试过这个.

python

3
推荐指数
1
解决办法
497
查看次数

标签 统计

python ×4

list ×2

augmented-assignment ×1

string ×1