[英]Why does append() and += give different results when I want to add a dictionary into a list in Python?
I want to append a dictionary germany
into a list travel_log
.我想将germany
字典附加到列表travel_log
中。
travel_log = [
{
"country": "France",
"visits": 12,
"cities": ["Paris", "Lille", "Dijon"]
}]
germany = {
"country": "Germany",
"visits": 5,
"cities": ["Berlin", "Hamburg", "Stuttgart"]
}
When I use travel_log += germany
, the result is当我使用travel_log += germany
时,结果是
[{'country': 'France', 'visits': 12, 'cities': ['Paris', 'Lille', 'Dijon']}, 'country', 'visits', 'cities']
. [{'country': 'France', 'visits': 12, 'cities': ['Paris', 'Lille', 'Dijon']}, 'country', 'visits', 'cities']
。
The values in germany disappeared.德国的价值观消失了。
But when I use travel_log.append(germany)
, the result is但是当我使用travel_log.append(germany)
时,结果是
[{'country': 'France', 'visits': 12, 'cities': ['Paris', 'Lille', 'Dijon']}, {'country': 'Germany', 'visits': 5, 'cities': ['Berlin', 'Hamburg', 'Stuttgart']}]
This is the correct one.这是正确的。
Why these two results are diffrent?为什么这两个结果不同?
Because +=
extends the list with another iterable, and iterating over a dict iterates over the keys (try print(list(germany))
).因为+=
使用另一个可迭代扩展列表,并且迭代 dict 迭代键(尝试print(list(germany))
)。
You'd get the same effect with travel_log.extend(germany)
.你会得到与travel_log.extend(germany)
相同的效果。
.append(x)
doesn't iterate over x
, it just appends it as-is to the list. .append(x)
不会迭代x
,它只是将其按原样附加到列表中。
The two results are different because +=
and .append
are designed to do completely different things.这两个结果是不同的,因为+=
和.append
旨在做完全不同的事情。
.append
adds a value to the end of a list. .append
将一个值添加到列表的末尾。 For example:例如:
a = [1, 2, 3]
a.append(4)
print(a)
# => [1, 2, 3, 4]
+=
adds all the values from another iterable to the end of the list - it does the same as .extend
. +=
将另一个可迭代的所有值添加到列表的末尾 - 它与.extend
相同。 If you tried to do a += 4
in the example above, it would error as 4
is not an iterable.如果您尝试在上面的示例中执行a += 4
,则会出错,因为4
不是可迭代的。
However, you are adding a dictionary, and a dictionary is an iterable - iterating over it will iterate over its keys.但是,您正在添加一个字典,而字典是一个可迭代的 - 迭代它会迭代它的键。 Hence +=
here does not error, but instead adds all the keys of the dictionary to the list (without erroring).因此+=
这里不会出错,而是将字典的所有键添加到列表中(没有出错)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.