Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python链接列表_Python - Fatal编程技术网

Python链接列表

Python链接列表,python,Python,我试图创建一个“append”方法,但出现以下错误: FAIL LinkedList/Combining [1] with [] yields list of length 1 Exception TypeError raised: unsupported operand type(s) for +: 'LinkedList' and 'NoneType' File "<string>", line 104, in _ 这就是我在Java中要做的: public LinkedL

我试图创建一个“append”方法,但出现以下错误:

FAIL LinkedList/Combining [1] with [] yields list of length 1
Exception TypeError raised: unsupported operand type(s) for +: 'LinkedList' and 'NoneType'
  File "<string>", line 104, in _
这就是我在Java中要做的:

public LinkedList append(LinkedList lst)
{
    if ( next == null )
    {
        return new LinkedList(value, lst);
   }
    else
    {
        return new LinkedList(value, next.append(lst));
    }
}

yield
仅在生成器上下文中使用。 在普通函数中,您只需返回一个带有
returnval
的值,因为只返回1个值

此外,如果要使用
+
运算符,正确的方法是
def\uuu添加\uuu(self,other)

如果您感兴趣,请提供一些有关发电机的简要信息 以下功能是发电机功能:

def yieldNumbers(limit);
    for i in range(limit):
        yield i 
生成器非常有用,因为它们允许您逐个请求值。这与下列情况相反:

def listNums(limit)
    r = []
    for i in range(limit):
        r.append(i)
    return r
def printNums((:
    print(1)
    yield 
    print(2)
    yield
    print(3)
    yield

>>> n = printNums()
>>> next(n)
1
>>> next(n)
2
>>> next(n)
3
>>> next(n)
StopIteration # that's an error raised when there's
# no more values left to yield
在这里,函数生成所有值并一次返回所有值。在处理大量数据时,这是一个问题,因为它可能会占用大量内存。相反,生成器,如我所说,只在调用时才产生1乘1的值:因此生成器函数产生一个值,并记住它在循环中的位置,然后从它停止的位置继续。考虑以下事项:

def listNums(limit)
    r = []
    for i in range(limit):
        r.append(i)
    return r
def printNums((:
    print(1)
    yield 
    print(2)
    yield
    print(3)
    yield

>>> n = printNums()
>>> next(n)
1
>>> next(n)
2
>>> next(n)
3
>>> next(n)
StopIteration # that's an error raised when there's
# no more values left to yield

生成器使用
next(gen)
方法,该方法调用生成器的
gen.\uuu next\uuu()
内部方法。如果要实现行为类似于迭代器的对象,这非常有用。然而,如果您想实现这一点,您应该定义名为
\uuuu iter\uuuuu
的方法,它通常只返回
self
self.next
->
self.next
?我认为您想要实现的是
\uuuu add\uuuuuu
,而不是
\uu append\uuu
+
操作符调用已定义的
\uuuuuuuuuuuuuuuuuuu
方法。我不认为
\uuuuuu append\uuuuu
会对任何操作符的行为产生任何影响;您不应该在这里实际使用
yield