如果数组包含输入,则消除数组内的列表

Eliminate list inside an array if it contains input

我最近开始学习 python 并使用数组。我需要检查我的数组中是否存在输入的代码,如果它确实删除了包含它的整个列表。我的代码如下:

room = 'F22'
array = [['F22', 'Single', 'Cash']]

def deleteReservation(room, array):
    print(array)
    for x in array:
        for i in x:
            if room in i:
                index = array.index(room)
                mode = validateNum(0, '1 To confirm, 2 to cancel.: ', 3)
                if mode == 1:
                    array = array.pop(index)
                    return array
                elif mode == 2:
                    return 'Canceled.'
        else:
            return "Reservation was not found."

但我不断收到以下错误:

Traceback (most recent call last):
index = array.index(room)
ValueError: 'F22' is not in list

我的猜测是错误在嵌套循环内部,但我找不到它。

试试这个


room = 'F22'
array = [['F22', 'Single', 'Cash']]

def deleteReservation(room, array):
    print(array)
    for x in array:
        if room in x:
            index = x.index(room)
            mode = validateNum(0, '1 To confirm, 2 to cancel.: ', 3)
            if mode == 1:
                array = array.pop(index)
                return array
            elif mode == 2:
                return 'Canceled.'
        else:
            return "Reservation was not found."

为什么会出现这个错误?

这一行有错误

array.index(room) # here array is for full list `[['F22', 'Single' 'Cash']]`, and you try to get the index of `F22`from this,

# as you loop through the array

for x in array:
    print(x) # here you get x = `['F22', 'Single' 'Cash']` this is the list from inside the array list, Hence you can use x.index('F22') 'cause `F22` present in x. not in array (array only has one element which is `['F22', 'Single' 'Cash']`.)



您应该使用 room 所在的整个数组来索引您的主数组。可以试试这个

room = 'F22'
array = [['F22', 'Single', 'Cash']]

def deleteReservation(room, array):
    print(array)
    for index,x in  enumerate(array):
        for i in x:
            if room == i:
                mode = validateNum(0, '1 To confirm, 2 to cancel.: ', 3)
                if mode == 1:
                    array = array.pop(index)
                    return array
                elif mode == 2:
                    return 'Canceled.'
        else:
            return "Reservation was not found."

deleteReservation(room,array)