Python:.append(0)

tmi*_*hty 6 python

我想问一下以下在Python中的作用。它取自http://danieljlewis.org/files/2010/06/Jenks.pdf

我已经输入了评论,告诉我我认为那里正在发生什么。

# Seems to be a function that returns a float vector
# dataList seems to be a vector of flat. 
# numClass seems to an int

def getJenksBreaks( dataList, numClass ):

    # dataList seems to be a vector of float. "Sort" seems to sort it ascendingly
    dataList.sort() 

    # create a 1-dimensional vector 
    mat1 = []

    # "in range" seems to be something like "for i = 0 to len(dataList)+1)
    for i in range(0,len(dataList)+1):

        # create a 1-dimensional-vector?
        temp = []
        for j in range(0,numClass+1):

            # append a zero to the vector?
            temp.append(0)

        # append the vector to a vector??
        mat1.append(temp)
Run Code Online (Sandbox Code Playgroud)

(……)

我有点困惑,因为在 pdf 中没有明确的变量声明。但是我认为并希望我能猜出变量。

Phi*_*ipD 4

是的,append() 方法将元素添加到列表末尾。我认为您对代码的解释是正确的。

但请注意以下事项:

x =[1,2,3,4]
x.append(5)
print(x)
    [1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)

尽管

x.append([6,7])
print(x)
    [1, 2, 3, 4, 5, [6, 7]]
Run Code Online (Sandbox Code Playgroud)

如果你想要类似的东西

    [1, 2, 3, 4, 5, 6, 7]
Run Code Online (Sandbox Code Playgroud)

你可以使用extend()

x.extend([6,7])
print(x)
    [1, 2, 3, 4, 5, 6, 7]
Run Code Online (Sandbox Code Playgroud)