我最近開始學習 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
我的猜測是錯誤在嵌套回圈內,但我找不到它。
uj5u.com熱心網友回復:
試試這個
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']`.)
uj5u.com熱心網友回復:
你應該用整個陣列索引你的主陣列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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/478933.html
