代码未按预期执行[For in cycle]

时间:2016-11-15 13:29:26

标签: python

为什么这不起作用?任何条目的实际结果为[]

def non_unique(ints):
    """
    Return a list consisting of only the non-unique elements from the list lst.

    You are given a non-empty list of integers (ints). You should return a
    list consisting of only the non-unique elements in this list. To do so
    you will need to remove all unique elements (elements which are
    contained in a given list only once). When solving this task, do not
    change the order of the list.

    >>> non_unique([1, 2, 3, 1, 3])
    [1, 3, 1, 3]
    >>> non_unique([1, 2, 3, 4, 5])
    []
    >>> non_unique([5, 5, 5, 5, 5])
    [5, 5, 5, 5, 5]
    >>> non_unique([10, 9, 10, 10, 9, 8])
    [10, 9, 10, 10, 9]
    """

    new_list = []
    for x in ints:
        for a in ints:
            if ints.index(x) != ints.index(a):
                if x == a:
                    new_list.append(a)
    return new_list

工作代码(不是来自我):

result = []
for c in ints:
  if ints.count(c) > 1:
    result.append(c)
return result

2 个答案:

答案 0 :(得分:1)

list.index将返回包含输入参数的第一个索引,因此如果x==a为真,那么ints.index(x)将始终等于ints.index(a) 。如果你想保持相同的代码结构,我建议使用enumerate跟踪循环中的指标,如下所示:

for x_ind, x in enumerate(ints):
    for a_ind, a in enumerate(ints):
        if x_ind != a_ind:
            if x == a:
                new_list.append(a)

尽管如此,我认为你的工作代码示例是完成相同任务的更好方法。

答案 1 :(得分:1)

尽管工作代码的示例是正确的,但如果遇到二次复杂性,则会使较大的列表变慢。我更喜欢s.th.像这样:

from nltk.probability import FreqDist

def non_unique(ints):
    fd = FreqDist(ints)
    return [x for x in ints if fd[x] > 1]

它在第一步中预先计算频率分布,然后选择所有非唯一元素。这两个步骤都具有O(n)性能特征。