python-3.x 当将子列表保存为变量然后追加到变量时,为什么主列表会受到影响

agxfikkp  于 2023-04-22  发布在  Python
关注(0)|答案(1)|浏览(99)

在这段代码中,变量“attractions for destination”在函数add_attraction中创建这个变量保存列表的子列表那么,为什么当我添加到这个保存的子列表时,它也添加到父列表呢(景点)。这可以在打印时看到()当函数被调用并且列表似乎被更新时的吸引力即使附加到的变量是“attractions_for_destination”变量。创建列表的子列表并单独附加到它总是反映到主列表上吗?这里

destinations = ["Paris, France", "Shanghai, China", "Los Angeles, USA", "Sao Paulo, Brazil", "Cairo, Egypt"]

test_traveler = ['Erin Wilkes', 'Shanghai, China', ['historical site', 'art']]

def get_destination_index(destination):
  destination_index = destinations.index(destination)
  return destination_index

def get_traveler_location(traveler):
  traveler_destination = traveler[1]
  traveler_destination_index = get_destination_index(traveler_destination)
  return traveler_destination_index

attractions = [[] for place in destinations]

def add_attraction(destination, attraction):
  destination_index = get_destination_index(destination)
  attractions_for_destination = attractions[destination_index]
  attractions_for_destination.append(attraction)

add_attraction("Los Angeles, USA", ['Venice Beach', ['beach']])
print(attractions)

其结果是:
[[],[],[['威尼斯海滩',['海滩']],[],[]]
为什么?

h43kikqp

h43kikqp1#

你在这里看到的行为的原因是与python中如何处理非平凡对象有关。python中的列表没有固定的大小,这意味着大量复制它可能会导致大的速度减慢。解决这个问题的方法是,而不是到处复制列表,引用被存储在适当的位置,并提供给访问它的变量。这样做的副作用是,如果您修改变量的值,这是一个存储在主列表中的列表,你正在改变主列表中引用所指向的值。这就是为什么从这个列表中获取的变量的任何更改都会反映在原始列表中。
如果你想复制一个列表,你可以查看copy模块,或者像newlist = [item for item in oldlist]这样做一个列表解析。
如果您有任何问题,请留下评论。

相关问题