Python 列表([])和 []

标签 python arrays list

from cs1graphics import *
from math import sqrt

numLinks = 50
restingLength = 20.0
totalSeparation = 630.0
elasticityConstant = 0.005
gravityConstant = 0.110
epsilon     = 0.001

def combine(A,B,C=(0,0)):
    return (A[0] + B[0] + C[0], A[1] + B[1] + C[1])

def calcForce(A,B):
    dX = (B[0] - A[0])
    dY = (B[1] - A[1])
    distance = sqrt(dX*dX+dY*dY)
    if distance > restingLength:
        stretch = distance - restingLength
        forceFactor = stretch * elasticityConstant
    else:
        forceFactor = 0
    return (forceFactor * dX, forceFactor * dY)                 #return a tuple


def drawChain(chainData, chainPath, theCanvas):
    for k in range(len(chainData)):
        chainPath.setPoint(Point(chainData[k][0], chainData[k][1]),k)
    theCanvas.refresh()                             #refresh canvas

chain = []                                                             #chain here
for k in range(numLinks + 1):
    X = totalSeparation * k / numLinks
    chain.append( (X,0.0) )

paper = Canvas(totalSeparation, totalSeparation)
paper.setAutoRefresh(False)
curve = Path()
for p in chain:
    curve.addPoint(Point(p[0], p[1]))
paper.add(curve)
graphicsCounter = 100

somethingMoved = True
while somethingMoved:
    somethingMoved = False
    oldChain = list(chain)                                             #oldChain here
    for k in range(1, numLinks):
        gravForce = (0, gravityConstant)
        leftForce = calcForce(oldChain[k], oldChain[k-1])
        rightForce = calcForce(oldChain[k], oldChain[k+1])
        adjust = combine(gravForce, leftForce, rightForce)
        if abs(adjust[0]) > epsilon or abs(adjust[1]) > epsilon:
            somethingMoved = True
        chain[k] = combine(oldChain[k], adjust)
    graphicsCounter -= 1
    if graphicsCounter == 0:
        drawChain(chain, curve, paper)
        graphicsCounter = 100

curve.setBorderWidth(2)
drawChain(chain, curve, paper)

有人告诉我 list([]) == []。那么为什么这段代码在做
oldChain = list(chain) 而不是 oldChain = chain

这是同一件事,所以无论哪种方式都没有关系吗?

最佳答案

list(chain) 返回chain的浅拷贝,等价于chain[:]

如果您想要列表的浅拷贝,请使用 list(),它有时也用于从迭代器中获取所有值。

y = list(x)y = x 的区别:


浅拷贝:

>>> x = [1,2,3]
>>> y = x         #this simply creates a new referece to the same list object
>>> y is x
True
>>> y.append(4)  # appending to y, will affect x as well
>>> x,y
([1, 2, 3, 4], [1, 2, 3, 4])   #both are changed

#shallow copy   
>>> x = [1,2,3] 
>>> y = list(x)                #y is a shallow copy of x
>>> x is y     
False
>>> y.append(4)                #appending to y won't affect x and vice-versa
>>> x,y
([1, 2, 3], [1, 2, 3, 4])      #x is still same 

深拷贝:

请注意,如果 x 包含可变对象,那么仅 list()[:] 是不够的:

>>> x = [[1,2],[3,4]]
>>> y = list(x)         #outer list is different
>>> x is y          
False

但内部对象仍然是对 x 中对象的引用:

>>> x[0] is y[0], x[1] is y[1]  
(True, True)
>>> y[0].append('foo')     #modify an inner list
>>> x,y                    #changes can be seen in both lists
([[1, 2, 'foo'], [3, 4]], [[1, 2, 'foo'], [3, 4]])

由于外部列表不同,因此修改 x 不会影响 y,反之亦然

>>> x.append('bar')
>>> x,y
([[1, 2, 'foo'], [3, 4], 'bar'], [[1, 2, 'foo'], [3, 4]])  

要处理此问题,请使用 copy.deepcopy

关于Python 列表([])和 [],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17599175/

相关文章:

python - 如何修剪掉数组元素的\x部分?

python : how to append new elements in a list of list?

list - 在 Kotlin 中转换后返回第一个非空值

python - 是否可以在 Selenium 和 Chrome 网络驱动器上禁用加载图像(仅限 jpg 和 png)?

python - 无法从网站下载 CSV 文件

Python 统计模型 : Using SARIMAX with exogenous regressors to get predicted mean and confidence intervals

python - Pycharm:Python Qt代码代码补全

python - 使用 OpenCV 在 Python 中反转图像

c - 难倒 : for loop to build an array not working, 忽略初始条件?

python - 将 2 个暗数组 'list of lists"输出到 python 中的文本文件