Python中文
首页
教程
问答
标签
搜索
登录
注册
python:my copy变量的更改会影响原始变量b
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>我有一个列表,我创建了一个副本,以便在保留原始列表的同时进行一些操作。但是,当我将<code>copy_list</code>设置为<code>org_list</code>时,它们变成了相同的东西,如果我改变<code>copy_list</code>,那么<code>org_list</code>也会改变。例如:</p> <pre><code>org_list = ['y', 'c', 'gdp', 'cap'] copy_list = org_list copy_list.<a href="https://www.cnpython.com/list/append" class="inner-link">append</a>('hum') print(copy_list) print(org_list) </code></pre> <p>回报</p> <pre><code>['y', 'c', 'gdp', 'cap', 'hum'] ['y', 'c', 'gdp', 'cap', 'hum'] </code></pre> <p>我不太清楚到底发生了什么,但看起来<code>org_list</code>实际上是把自己传递给了<code>copy_list</code>,所以它们实际上是一样的。</p> <p>有没有一种方法可以制作一份独立的组织列表副本,而不必做一些笨拙的事情,比如:</p> <pre><code>copy_list = [] for i in org_list: copy_list.append(i) </code></pre> <p>我这么说是因为我对其他类型的变量也有同样的问题,例如pandas数据框。</p>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>这是因为在python中设置变量实际上设置了对该变量的引用。几乎每个学习python的人都会在某个时候遇到这种情况。解决方案只是复制列表:</p> <pre><code>copy_list = org_list[:] </code></pre>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
如何在乒乓球比赛中预测球的轨迹,对于AI球拍预测?
9 回答
如何在乒乓球游戏中阻止球
2 回答
如何在乘法和模中不乘空间?
10 回答
如何在乘法和除以2个不同的数字之间进行交换?
1 回答
如何在也是数据一部分的单个字符上拆分大字符串
4 回答
如何在乾草堆中找到針,有更好的解決方案嗎?
3 回答
如何在事件wxWidgets中传递自定义数据
10 回答
如何在事件中使用lambda i=i?
10 回答
如何在事件中心只接收最近的数据
4 回答
如何在事件发生之前保持云函数运行?
8 回答
如何在事件发生后使页面重定向到同一页面
6 回答
如何在事件回调之间保持python生成器的状态
5 回答
如何在事件处理程序(pythonsocket、sphinx)中保留docstring
2 回答
如何在事件处理程序中更改wxRichTextCtrl的光标位置?
8 回答
如何在事件处理程序中访问外部对象?
4 回答
如何在事件循环中将协程打包为正常函数?
8 回答
如何在事件循环之外运行协同程序?
1 回答
如何在事件循环结束时为并发未来的所有线程调用类方法?
10 回答
如何在事件文件中只保留一份摘要?
7 回答
如何在事件模板中添加事件
6 回答