【发布时间】:2016-03-11 02:31:55
【问题描述】:
这是我必须做的一个问题:
我们将实现一个非常有用的函数,称为 group。
group 接受一个事物列表并返回一个组列表,其中每个组由列表中所有相等的连续元素组成。
例如:
group([1, 1, 1, 2, 3, 1, 1]) == [[1, 1, 1], [2], [3], [1, 1]]
group([1, 2, 1, 2, 3, 3]) == [[1], [2], [1], [2], [3, 3]]
这是我最初的解决方案:
def group(int_list):
group_list = []
current_list = []
for i in range(len(int_list)):
if int_list[i] not in current_list:
if len(current_list) != 0:
group_list.append(current_list)
del current_list[:]
current_list.append(int_list[i])
else:
current_list.append(int_list[i])
group_list.append(current_list)
return group_list
我得到的输出:
[[1, 1], [1, 1], [1, 1], [1, 1]]
在花了大约 30 分钟试图找出问题后,我将第 9 行从 group_list.append(current_list) 更改为 group_list.append(current_list[:]),令人惊讶的是,魔法奏效了。我得到了正确的输出:
[[1, 1, 1], [2], [3], [1, 1]]
所以我想我的问题是 current_list 和 current_list[:] 有什么区别?
【问题讨论】:
-
修复原始代码的另一种方法是将
del current_list[:]更改为current_list = [],这样下次你追加current_list时它会是一个不同的列表(即不需要做一个浅拷贝)。