问题描述
x=[1,2,3]
x.extend('a')
输出:
x is [1,2,3,'a']
但是,当我做到以下几点:
But when I do the following:
[1,2,3].extend('a')
输出:
None
为什么在列表参考名单上延伸的工作,但不是?
Why does extend work on a list reference, but not on a list?
我发现这是因为我想一个数组listB追加到为listA试图listC扩展到数组listB。
I found this because I was trying to append a listB to a listA while trying to extend listC to listB.
listA.append([listB[15:18].extend(listC[3:12])])
假如清单不能直接所附/延伸。什么是最流行的变通形式解决这个问题?
Supposing lists cannot be directly appended / extending. What is the most popular work around form for resolving this issue?
推荐答案
list.extend
就地修改列表中,并没有返回值,从而导致无
。在第二种情况下,这是一个临时的名单正在扩展它的行后立即消失,而在第一种情况下,可以通过 X
引用。
list.extend
modifies the list in place and returns nothing, thus resulting in None
. In the second case, it's a temporary list that is being extended which disappears immediately after that line, while in the first case it can be referenced via x
.
一个数组listB追加到为listA试图listC扩展到数组listB。
而不是使用延长
,你可能会想尝试这样的:
Instead of using extend
, you might want to try this:
listA.append(listB[15:18] + listC[3:12])
或用做它在多个简单的线条延长
如果要实际修改数组listB
或 listC
。
Or do it in multiple simple lines with extend
if you want to actually modify listB
or listC
.
这篇关于Python的 - 直接扩展列表导致无,为什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!