14

私は Python の初心者です。私の投稿に対して否定的な考えを持っている人は、退出してください。私はただここで助けを求め、学ぼうとしているだけです。0 と 1 の単純なデータ セット内でチェックしようとしています。これは、建物内のゾーンを定義するためにフロア プランでボイドとソリッドを定義するために使用されます。最終的には、0 と 1 が座標で置き換えられます。

このエラーが発生しています: ValueError: [0, 3] is not in list

あるリストが別のリストに含まれているかどうかを確認しているだけです。

currentPosition's value is  [0, 3]
subset, [[0, 3], [0, 4], [0, 5], [1, 3], [1, 4], [1, 5], [2, 1], [3, 1], [3, 4], [3, 5], [3, 6], [3, 7]]

コード スニペットは次のとおりです。

def addRelationship(locale, subset):
    subset = []; subSetCount = 0
    for rowCount in range(0, len(locale)):
        for columnCount in range (0, int(len(locale[rowCount])-1)):
            height = len(locale)
            width = int(len(locale[rowCount]))
            currentPosition = [rowCount, columnCount]
            currentVal = locale[rowCount][columnCount]
            print "Current position is:" , currentPosition, "=", currentVal

            if (currentVal==0 and subset.index(currentPosition)):
                subset.append([rowCount,columnCount])
                posToCheck = [rowCount, columnCount]
                print "*********************************************Val 0 detected, sending coordinate to check : ", posToCheck

                newPosForward = checkForward(posToCheck)
                newPosBackward = checkBackward(posToCheck)
                newPosUp = checkUpRow(posToCheck)
                newPosDown = checkDwnRow(posToCheck)

私はsubset.index(currentPosition)を使用して[0,3]がサブセットにあるかどうかを確認して確認していますが、[0,3]を取得していませんリストにありません。どうして?

4

4 に答える 4

26

同じエラーをスローする同等のコードをいくつか示しましょう。

a = [[1,2],[3,4]]
b = [[2,3],[4,5]]

# Works correctly, returns 0
a.index([1,2])

# Throws error because list does not contain it
b.index([1,2])

何かがリストに含まれているかどうかだけを知る必要がある場合は、次のinようにキーワードを使用します。

if [1,2] in a:
    pass

または、正確な位置が必要であるが、リストに含まれているかどうかがわからない場合は、プログラムがクラッシュしないようにエラーをキャッチできます。

index = None

try:
    index = b.index([0,3])
except ValueError:
    print("List does not contain value")
于 2012-08-23T17:34:03.877 に答える
1

subset.index(currentPosition)が のインデックス 0 にあるFalseときに評価されるため、その場合、条件は失敗します。あなたが望むのはおそらく次のとおりです。currentPositionsubsetif

...
if currentVal == 0 and currentPosition in subset:
...
于 2012-08-23T17:32:34.440 に答える