【发布时间】:2019-09-19 14:02:14
【问题描述】:
我们有以下列表作为输入:
[[-5, -1], [1, -5], [5, -1]]
我创建了一个函数,它将clist 作为一个列表,number 一个我想从列表中删除的随机数。
该函数应删除包含给定number 的所有嵌套列表,并删除嵌套列表中的否定 number
def reduce(self, clist, number):
self.temp = list(clist)
# remove the nested list that contain the given number
for item in clist:
if number in item:
self.temp.remove(item)
# remove the negative number within the nested list
for obj in self.temp:
try:
obj.remove(-number)
except:
pass
return self.temp
让我们选择1 作为number 并运行代码。
-
第一个
for循环将删除所有包含给定数字的嵌套列表,并将获得以下内容:self.temp = [[-5, -1], [5, -1]]clist = [[-5, -1], [1, -5], [5, -1]] -
第二个
for循环应该删除嵌套列表中所有否定的number,但我们得到以下结果:self.temp = [[-5], [5]]clist = [[-5], [1, -5], [5]]
我不明白为什么clist 在我处理第二个for 循环时会受到影响,尤其是在我处理self.temp 列表时?它应该没有参考原始列表,但我遗漏了一些东西。帮助?
【问题讨论】:
-
你能给出完整的代码吗
-
@hsnsd 不幸的是,没有,因为这是我的任务的一部分。但我可以告诉你其他可能会影响的部分,但到目前为止,这是影响我结果的部分。
标签: python-3.x list nested-lists