2016-11-15 4 views
-2

なぜこれが機能しないのですか?実際の結果は、任意のエントリに対して[]です。コードが期待通りに実行されない[サイクル中]

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 

(ない私から)ワーキングコード:x==aが真であるかのよう

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

'ints.index(x)!= ints.index(a)'と 'x == a'という条件を同時に満たすことはできません。私はあなたが彼らがどのようになるかもしれないと想像していません。 – khelwood

+0

どうしてなぜこんなことができないのか分かりません。最初はインデックス用、2番めの値用です。 –

答えて

1

list.indexints.index(a)その後、ints.index(x)が常に等しくなり、入力パラメータが含まれてい最初のインデックスを返します。

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) 

、けれどもそれは価値がある何のために、私が働いて、コードのあなたの例だと思う:あなたは同じコードの構造を維持したい場合は、私はのようにenumerateを使用してループ内なインデックスを追跡するお勧めします同じタスクを達成するより良い方法。

1

作業コードの例は正しいですが、2次的な複雑さに悩まされていると、大きなリストの処理速度が遅くなります。私はs.thを好むだろう。

これは、最初のステップで頻度分布を事前に計算してから、すべての固有でない要素を選択します。両方のステップにはO(n)性能特性があります。

関連する問題