我最近开始学习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)