python列表,将某些内容添加到列表会更改整个内容吗? [英] python lists, appending something to the list changes the entire thing?

查看:74
本文介绍了python列表,将某些内容添加到列表会更改整个内容吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图在python ..中实现选择排序,并将每个迭代的结果附加到要打印的列表的末尾.我的代码正确地对数字列表进行排序,但是当我将其附加到相同的列表时最后,它会更改所有其他列表.

so im trying to implement selection sort in python.. and im appending the result of each iteration to a list to print at the end.. my code sorts the list of numbers properly but when i append it to the same list at the end it changes all other lists..

def s_sort(numbers):
  alist=[]
  #do actual sorting here and swap numbers/index if neccessary

       alist.append(numbers)
  return alist

def main():
    numbers=[5,7,3]
    print(s_sort(numbers))
main()

返回的列表是[[3,5,7],[3,5,7]]而不是[[3,7,5],[3,5,7]] !!!! 当我以某种方式添加到列表时,两个列表的列表内容都会改变!

the alist returned is [[3,5,7],[3,5,7]] instead of [[3,7,5],[3,5,7]] !!!! somehow when i do the append to alist, the content of alist changes for both lists!

推荐答案

使用切片制作副本

newlist = alist[:]

在您的情况下,我猜是:

In your case, I guess it's:

alist.append(numbers[:])

这篇关于python列表,将某些内容添加到列表会更改整个内容吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆