可能重复:
Python列表扩展和变量赋值
字符串的模拟成立:
string1 = 'abc'
''.join(string1) == string1 # True
Run Code Online (Sandbox Code Playgroud)
那为什么不成立呢:
list1 = ['a', 'b', 'c']
[].extend(list1) == list1 # AttributeError: 'NoneType' object has no attribute 'extend'
Run Code Online (Sandbox Code Playgroud)
type([])返回列表.为什么它会被视为NoneType而不是具有extend方法的列表?
这是一个学术问题.我不会这样做是常规代码,我只是想了解.
Sil*_*Ray 11
因为list.extend()修改了列表并且没有返回列表本身.为了得到你的期望,你需要做的是:
lst = ['a', 'b', 'c']
cplst = []
cplst.extend(lst)
cplst == lst
Run Code Online (Sandbox Code Playgroud)
您引用的功能并不是真正类似的. join()返回一个新的字符串,该字符串是通过将迭代器的成员与正在join编辑的字符串连接而创建的.类似的list操作看起来更像是:
def JoiningList(list):
def join(self, iterable):
new_list = iterable[0]
for item in iterable[1:]:
new_list.extend(self)
new_list.append(item)
return new_list
Run Code Online (Sandbox Code Playgroud)