Python:删除列表中的重复项传递到新列表(递归)

时间:2012-11-22 04:45:55

标签: python list recursion duplicates erase

我正在努力学习递归。我试图将列表作为参数并返回一个新列表,其中旧列表中的值仅在新列表中出现一次。 我已经在这里待了几个小时但是一直卡住了。

3 个答案:

答案 0 :(得分:2)

if (old_list[0] not in new_list):

请注意,此时new_list将始终为空,因此此条件将始终为true,并且所有元素都将添加到新列表中。

您的代码只是稍微调整一下,无法正常运行。而不是检查项目是否在new_list中,我认为您应该检查它是否在旧列表的其余部分中

if (old_list[0] not in old_list[1:]):

答案 1 :(得分:1)

我认为问题出现在第二个if语句中:

def bag_to_set(old_list):
    new_list = []
    if old_list == []:
        new_list = []
    else:
        if (old_list[0] not in old_list[1:]):
            new_list = [old_list[0]] + bag_to_set(old_list[1:])
        else:
            new_list = bag_to_set(old_list[1:])
    return new_list 

通过在条件

中将old_list替换为old_list [1:],看起来这样可以修复它

答案 2 :(得分:0)

愚蠢的问题:为什么第二个如果在其他之后呢?我认为这可能会更顺畅一点:

if old_list == []:
  new_list == []
elif old_list[0] not in old_list[1:]:
   new_list = [old_list[0]] + bag_to_set(old_list[1:])
else: 
   new_list = [old_list[0]] + bag_to_set(old_list[1:])

这避免了1级嵌套。一个小问题,但我认为可能值得折腾...