python列表,将某些内容添加到列表会更改整个内容吗?

编程入门 行业动态 更新时间:2024-10-22 11:36:39
本文介绍了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列表,将某些内容添加到列表会更改整个内容吗?

本文发布于:2023-11-27 08:10:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1637224.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:内容   列表   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!