为什么[].extend(list1)不创建与list1相同的列表?

2024-04-23 07:05:13 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
Python list extension and variable assignment

字符串的模拟是正确的:

string1 = 'abc'
''.join(string1) == string1 # True

为什么这不成立:

list1 = ['a', 'b', 'c']
[].extend(list1) == list1 # AttributeError: 'NoneType' object has no attribute 'extend'

type([])返回列表。为什么它会被认为是一个NoneType而不是一个拥有extend方法的列表?你知道吗

这是一个学术问题。我不会这样做,这是常规代码,我只是想了解。你知道吗


Tags: and字符串列表extensionvariablelistabcjoin
3条回答

您正在尝试将扩展名的返回值与列表进行比较。extend是就地操作,意味着它不返回任何内容。你知道吗

另一方面,join实际上返回操作的结果,因此可以比较这两个字符串。你知道吗

>>> first = [1,2,3]
>>> second = []
>>> second.extend(first)
>>> first == second
True

因为list.extend()就地修改列表,而不返回列表本身。你需要做的是:

lst = ['a', 'b', 'c']
cplst = []
cplst.extend(lst)
cplst == lst

你引用的函数其实并不相似。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

相关问题 更多 >