Исправление ошибки TypeEr:
Интерпретатор сообщает вам точно , где и почему возникла проблема.Вот ваши MVCE :
>>> range[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable
Вы не можете использовать квадратные скобки или индексы (т. Е. []
) на встроенном range
.Вместо этого используйте круглые скобки (()
):
>>> range(1)
range(0, 1)
Поэтому измените эту строку:
for x in range[len(listLicencePlates)] # bad news, range[...]
на
for x in range(len(listLicencePlates)) # Better, range(...)
и вы пройдетеTypeError
.
Исправление проблемы с ядром:
Я предполагаю, однако, что результат, полученный из этого исправления , не , что вы хотите.Это вывод:
[['V', 'F', '1', '0', '0', '5', '5'], ['V', 'F', '1', '0', '0', '5', '5'], ['V', 'F', '1', '0', '0', '5', '5'], ['V', 'F', '1', '0', '0', '5', '5'], ['V', 'F', '1', '0', '0', '5', '5']]
Что не выглядит полезным.
Я думаю, что вы , вероятно, хотите, это массив bools
, где каждый bool
описывает, соответствует ли табличка символьному символу, а "?"
представляет собой символ подстановки.
Давайте попробуем более Pythonic и менее C-стиль подход к проблеме с некоторыми чрезвычайно подробными комментариями:
def match_list2(witnessed_plate, license_plates):
matching_plates = []
# just loop through the items, no need for range/indices
for possible_match in license_plates:
# If they match, create 2-elt list with
# the plate as first elt and whether or not it matches as second
# Worry about do_plates_match later. Just get the high level logic
# down pat and sound first.
matching_plates.append([possible_match,
do_plates_match(possible_match, witnessed_plate)])
return matching_plates
def do_plates_match(plate1, plate2): # Define if they match (the time to worry is upon us)
# Loop through characters from plate1 and plate2 simultaneously
for first_char, second_char in zip(plate1, plate2):
if first_char == "?" or second_char == "?":
# If we get a question mark, go to the next character
continue
elif first_char != second_char:
# If they don't match at *some* character,
# we know they can't match regardless of what's next, so return False
return False
# Only way to get here is we must have matched for all characters, return True.
return True
и для тех, кто находит комментарии отвлекающими и предпочитает сразу же прочитать код:
def match_list2(witnessed_plate, license_plates):
matching_plates = []
for possible_match in license_plates:
matching_plates.append([possible_match, do_plates_match(possible_match, witnessed_plate)])
return matching_plates
def do_plates_match(plate1, plate2):
for first_char, second_char in zip(plate1, plate2):
if first_char == "?" or second_char == "?": continue
elif first_char != second_char: return False
return True
Теперь звонит:
plate = "VF???55"
print("Plate: ", plate)
print(match_list2(plate,["VX33322","VF12355","VF77455","DA?????","VF10055"]))
выводит:
Plate: VF???55
[['VX33322', False], ['VF12355', True], ['VF77455', True], ['DA?????', False], ['VF10055', True]]
четко показывает, какие пластины соответствуют, а какие нет.
HTH.