简体   繁体   English

list + = str和list + = str有什么区别,

[英]What is the difference between list += str and list += str,

Today I noticed a strange behavior while doing some python list operations. 今天我在做一些python列表操作时发现了一个奇怪的行为。

Lets say, 可以说,

a = []
b = 'xy'

When I do, a += b the interpreter returns: 当我这样做时,解释器返回+ = b:

a += b
a == ['x', 'y']

but when I do, a += b, (with a comma) the interpreter returns a = ['xy'] 但当我这样做时,+ = b,(用逗号)解释器返回= ['xy']

a += b,
a == ['xy']

Can someone please explain what is happening here. 有人可以解释一下这里发生了什么。

a += b

When a is a list, this operation is similar to a.extend(b) . a是列表时,此操作类似于a.extend(b) So it iterates the object b , appending each element to a . 所以它迭代对象b ,将每个元素追加到a

If you iterate the string 'xy' , it yields two elements 'x' and 'y' . 如果你迭代字符串'xy' ,它会产生两个元素'x''y'

If you iterate the tuple 'xy', , it yields one element 'xy' . 如果你迭代元组'xy', ,它会产生一个元素'xy'

The line 这条线

a += b,

is equivalent to 相当于

a += (b, )

It creates a tuple with one item. 它创建一个带有一个项目的元组。 If it is added, the item 'xy' it added to a . 如果添加,则将项目'xy'添加到a

If you add a string like 'xy' it counts as a sequence of characters on it's own and every sequence item (character) is added individually to a . 如果你添加一个像'xy'这样的字符串,它就会被视为一个字符序列,并且每个序列项(字符)都被单独添加到a字符串中。

So basically the comma wraps b into a tuple. 所以基本上逗号将b包装成一个元组。

Comma creates tuple - so a += b, means the same as a += (b,) 逗号创建tuple - 所以a += b,表示与a += (b,)

a += ('xy', )

You add tuple with one element so it almost like 你添加一个元素的元组,所以它几乎像

a += ['xy']

so you have 所以你有了

a = [] + ['xy']

which gives result 给出了结果

a = ['xy']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM