相关疑难解决方法(0)

什么时候"i + = x"与Python中的"i = i + x"不同?

我被告知+=可以有不同于标准符号的效果i = i +.有没有在这情况下i += 1会从不同i = i + 1

python operators

210
推荐指数
3
解决办法
5万
查看次数

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

+=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万
查看次数

Python就地操作符函数与标准操作符函数有何不同?

为什么不operator.iadd(x, y)等同z = x; z += y那有什么operator.iadd(x, y)不同operator.add(x, y)

来自文档:

许多操作都有"就地"版本.与通常的语法相比,以下函数提供了对原位运算符的更原始的访问; 例如,语句x + = y等于x = operator.iadd(x,y).另一种说法是说z = operator.iadd(x,y)相当于复合语句z = x; z + = y.

相关问题,但我对Python类方法不感兴趣; 只是内置Python类型的常规运算符.

python function operator-keyword

13
推荐指数
1
解决办法
1万
查看次数

+和+ =运算符不同?

>>> c = [1, 2, 3]
>>> print(c, id(c))
[1, 2, 3] 43955984
>>> c += c
>>> print(c, id(c))
[1, 2, 3, 1, 2, 3] 43955984
>>> del c
>>> c = [1, 2, 3]
>>> print(c, id(c))
[1, 2, 3] 44023976
>>> c = c + c
>>> print(c, id(c))
[1, 2, 3, 1, 2, 3] 26564048
Run Code Online (Sandbox Code Playgroud)

有什么不同?是+ =和+不应该仅仅是语法糖?

python list operators

4
推荐指数
1
解决办法
457
查看次数

组合列表中的元素:似乎python以两种不同的方式处理相同的项目,我不知道为什么

我正在通过CodeAcademy工作,我有一个问题,那里没有答案.分配是获取列表列表并列出其所有元素的单个列表.下面的代码是我的答案.但我不明白为什么"item"被视为该代码列表中的元素,而(请参阅下面的评论)...

m = [1, 2, 3]
n = [4, 5, 6]
o = [7, 8, 9]

def join_lists(*args):
    new_list = []
    for item in args:        
        new_list += item
    return new_list


print join_lists(m, n, o)
Run Code Online (Sandbox Code Playgroud)

...下面代码中的"项目"被视为整个列表而不是列表中的元素.下面的代码给出了输出:

 [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Run Code Online (Sandbox Code Playgroud)

我也尝试使用:new_list.append(item [0:] [0:])认为它将遍历索引和子索引,但它给出了相同的结果.我只是不明白这是如何被解释的.

m = [1, 2, 3]
n = [4, 5, 6]
o = [7, 8, 9]


def join_lists(*args):
    new_list = []
    for item in args:        
        new_list.append(item)
    return new_list


print join_lists(m, n, o) …
Run Code Online (Sandbox Code Playgroud)

python list python-2.7

0
推荐指数
1
解决办法
158
查看次数