Python索引错误值不在列表中...在.index(value)上 [英] Python index error value not in list...on .index(value)

查看:384
本文介绍了Python索引错误值不在列表中...在.index(value)上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的初学者,对于那些对我的帖子持负面想法的人,请离开.我只是在这里寻求帮助并试图学习.我试图在一个简单的数据集中检查0和1.这将用于在平面图上定义空隙和实体,以定义建筑物中的区域...最终将0和1替换为坐标.

I am a beginner at Python, and to those who holds negative thoughts against my post, please leave. I am simply seeking help here and trying to learn. I'm trying to check within a simple data set the 0s and 1s. This will be used towards defining voids and solids on floor plans to define zones in buildings... eventually 0s and 1s will be swapped out with coordinates.

我收到此错误:ValueError:[0,3]不在列表中

I am getting this error: ValueError: [0, 3] is not in list

我只是在检查一个列表是否包含在另一个列表中.

I am simply checking if one list is contained in the other.

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]不在列表中.怎么会来?

I am using subset.index(currentPosition) to check and see if [0,3] is in subset but getting the [0,3] is not in list. How come?

推荐答案

让我们展示一些引发相同错误的等效代码.

Let's show some equivalent code that throws the same error.

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 all you need to know is whether something is contained in a list, use the keyword in like this.

if [1,2] in a:
    pass

或者,如果您需要确切的位置,但是不知道列表是否包含该位置,则可以捕获该错误,因此程序不会崩溃.

Alternatively, if you need the exact position but don't know if the list contains it, you can catch the error so your program does not crash.

index = None

try:
    index = b.index([0,3])
except ValueError:
    print("List does not contain value")

这篇关于Python索引错误值不在列表中...在.index(value)上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆