1

私は CS クラスに小さなタスクを設定しました。このタスクでは、Python でメソッドを記述して、リスト内の最大インデックス位置 (インデックス 50 まで) の項目を削除する必要があります。

以下に示すように、メソッドを作成しようとしましたが、メソッドの最後にリストを出力しようとすると、削除されたプライム インデックス位置の値を含むリストが返されるはずですが、単に完全なリストが返されるだけです。 (番号 1 ~ 50)。

私の機能:

def listDelete(list):
    for i in list:
        if i %2 != 0 & i % 3 != 0:
            del list[i]
return list

そして、次を使用して関数を呼び出します。

listDelete(range(1,50))

私はPythonに非常に慣れていないので、これが非常に単純な修正または明らかなエラーである場合はお詫びしますが、どんな助けも大歓迎です!

4

5 に答える 5

0

これはどう?

import numpy as np

def listDelete(list):
    for i in list:
        if (i %2 != 0 and i % 3 != 0):
            list[i] = 0
    return list[np.nonzero(list)]

次のように呼び出すことができます:

listDelete(np.arange(1,51))
于 2015-02-19T17:41:43.310 に答える
0

使用する要件(コメントでdel言及したもの)を質問に追加することをお勧めします。

とにかく、これが私がそれを行う方法です。

def primesTo50():
    '''Generator for prime numbers up to 50'''
    primes = {2, 3, 5, 7, 9, 11 , 13 , 17, 19, 23, 29, 31, 37, 41, 43, 47}
    yield from primes

def delIndices(L, indices, maxIndex = None):
    '''Delete indices of the list up to list length or to the 
    max index if it is provided'''
    if maxIndex is None:
        maxIndex = len(L) - 1
    indices_set = set(sorted(indices)) #don't try to delete the same index twice
    for i in reversed(range(maxIndex + 1)): #must delete in reverse order
        if i in indices_set: #check if i is in the indices to be removed
            try:
                del L[i]
            except IndexError: #ignore error from trying to delete invalid indices
                pass
    return L

#testing
print(delIndices([1,2,3,4], primesTo50(), 50)) # [1, 2]
print(delIndices([1,2,3,4], (0,100), 200)) # [2,3,4]

次のような素数ジェネレーターを実行することもできます。

def primes(max):
    '''Generator for prime numbers up to (not including) max'''
    r = range(max)
    for i in r:
        divisors = range(2, i)
        prime = True
        for d in divisors:
            if r%d == 0:
                prime = False
                break
        if prime:
            yield i

この問題には他にも多くの優れた解決策があります。私はこれを非常に迅速に作成しました(テストしていません-非常に遅いと確信しています)。素数の生成は数論の独自の分野であるため、IMO では、上記のように 50 までの素数をリストするだけの方がはるかに優れています。

于 2015-02-19T18:57:38.090 に答える