Python 从嵌套列表中仅删除列表中的元素
我有一个Python中的列表列表,例如
colours = [['1', '2', '3'], ['1', '2', '3'], ['1', '2', '3']]
所有三个列表开头都是相同的。我想从第一个列表中删除第一个 1,这样我就有了,
colours = [['2', '3'], ['1', '2', '3'], ['1', '2', '3']]
但无论我尝试什么,都会从每个列表中删除 1。
我尝试执行 colours[0].remove('1')
但结果是
colour = [['2', '3'], ['2', '3'], ['2', '3']]
我该怎么做?
我将颜色定义为:
list = ['1', '2', '3']
for i in range(3):
colours.append(list)
I have a list of lists in Python, such as
colours = [['1', '2', '3'], ['1', '2', '3'], ['1', '2', '3']]
All three lists are the same at the beginning. I want to remove the first 1 from the first list so that I have
colours = [['2', '3'], ['1', '2', '3'], ['1', '2', '3']]
but whatever I tried will remove the 1 from every list.
I tried doing colours[0].remove('1')
but then the result is
colour = [['2', '3'], ['2', '3'], ['2', '3']]
How can I do it?
I have defined colours as:
list = ['1', '2', '3']
for i in range(3):
colours.append(list)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须在某处循环运行它才能删除元素。
colors[0].remove('1') 很好。
c = [['1', '2', '3'], ['1', '2', '3'], ['1', '2', '3']]
c[0].remove('1')
打印(三)
[['2', '3'], ['1', '2', '3'], ['1', '2', '3']] --输出
You must be running it in a loop somewhere to remove the elements.
colours[0].remove('1') is good.
c = [['1', '2', '3'], ['1', '2', '3'], ['1', '2', '3']]
c[0].remove('1')
print (c)
[['2', '3'], ['1', '2', '3'], ['1', '2', '3']] --output
这对我来说听起来很奇怪,我进行了快速测试:
如果问题仍然存在,请使用更多信息更新您的问题
That sounds strange to me, I ran a quick test:
Update your question with more information if the issue persists
根据评论中的代码:
这将添加相同的列表 3 次。因此,当您使用:
您基本上是从原始列表中删除
1
。因此它也适用于各种颜色。这是因为所有颜色列表都指向内存中的同一位置。我的建议是,首先不要使用变量名称
list
,因为它会隐藏内置list
。其次,要构建您想要的列表,每次迭代使用不同的列表:或者使用理解:
As per your code in the comment:
This is adding the same list 3 times. Therefore when you use:
You are basically removing
1
from the original list. Therefore it is applied across colours as well. This is because all the lists in colours point to the same location in memory.My suggestion is, first don't use the variable name
list
as it shadows the builtinlist
. Second to build the list you intended, use different lists every iteration:Or using a comprehension: