Python IndexError:元组超出范围

时间:2015-07-16 07:25:37

标签: python tuples

有人可以帮我这个吗?

我已经在线查看并已经在Stackoverflow上了。 我也使用了PyCharm调试器,但这也没有让我更进一步。我确实运行了调试器,但我无法找到问题。 在调试时我注意到我没有在make_boarding_cards中获得任何值。在_passenger_seats中,我确实得到了一个值 我的猜测是问题应该在_passenger_seats中的某个地方,但我找不到它。 我不得不说我是Python的新手,所以在不久的将来我需要一些帮助。

这是来自Python控制台的错误消息:

>>> from airtravel import *
>>> f = make_flight()
>>> f.make_boarding_cards(console_card_printer)
Traceback (most recent call last):
  File "/usr/lib/python3.4/code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "/home/johanvergeer/Documenten/Training/Pluralsight/Python-Fundamentals/airtravel.py", line 104, in make_boarding_cards
    card_printer(passenger, seat, self.number(), self.aircraft())
  File "/home/johanvergeer/Documenten/Training/Pluralsight/Python-Fundamentals/airtravel.py", line 150, in console_card_printer
    "  |".format(passenger, flight_number, seat, aircraft)
IndexError: tuple index out of range

这是我的代码: 最后两行仅用于调试目的。

class Flight:
    """A flight with a particular passenger aircraft"""

    def __init__(self, number, aircraft):
        if not number[:2].isalpha():
            raise ValueError("No airline code in '{}'".format(number))
        if not number[:2].isupper():
            raise ValueError("Invalid airline code '{}'".format(number))
        if not (number[2:].isdigit() and 4 >= len(number[2:]) >= 3):
            raise ValueError("Invalid route number '{}'".format(number))
        self._number = number
        self._aircraft = aircraft

        rows, seats = self._aircraft.seating_plan()
        self._seating = [None] + [{letter: None for letter in seats} for _ in
                                  rows]

    def number(self):
        return self._number

    def airline(self):
        return self._number[:2]

    def aircraft(self):
        return self._aircraft

    def _parse_seat(self, seat):
        """Parse a seat designator into a valid row and letter.

        Args:
            seat: a seat designator such as 12F.

        Returns:
            A tuple containing an integer and a string for row and seat.
        """
        row_numbers, seat_letters = self._aircraft.seating_plan()

        letter = seat[-1]
        if letter not in seat_letters:
            raise ValueError("Invalid seat letter {}".format(letter))

        row_text = seat[:-1]
        try:
            row = int(row_text)
        except ValueError:
            raise ValueError("Invalid seat row {}".format(row_text))

        if row not in row_numbers:
            raise ValueError("Invalid row number {}".format(row))
        return row, letter

    def allocate_seat(self, seat, passenger):
        """Allocate a seat to a passenger.

        Args:
            seat: A seat designator such as '12C' or '21F'.
            passenger: The passenger name.

        Raises:
            ValueError: If the seat is unavailable.
        """

        row, letter = self._parse_seat(seat)

        if self._seating[row][letter] is not None:
            raise ValueError("Seat {} already occupied".format(seat))

        self._seating[row][letter] = passenger

    def relocate_passenger(self, from_seat, to_seat):
        """Relocate a passenger to a different seat.

        Args:
            from_seat: The existing seat assigned to the passenger to be moved.
            to_seat: The new seat designator.
        """

        from_row, from_letter = self._parse_seat(from_seat)

        if self._seating[from_row][from_letter] is None:
            raise ValueError(
                "No passenger to relocate in seat {}".format(from_seat))

        to_row, to_letter = self._parse_seat(to_seat)

        if self._seating[to_row][to_letter] is not None:
            raise ValueError("Seat {} is already occupied".format(to_seat))

        self._seating[to_row][to_letter] = self._seating[from_row][from_letter]
        self._seating[from_row][from_letter] = None

    def num_available_seats(self):
        return sum(sum(1 for s in row.values() if s is None)
                   for row in self._seating
                   if row is not None)

    def make_boarding_cards(self, card_printer):
        for passenger, seat in sorted(self._passenger_seats()):
            card_printer(passenger, seat, self.number(), self.aircraft())

    def _passenger_seats(self):
        """ An iterable series of passenger seating allocations"""
        row_numbers, seat_letters = self._aircraft.seating_plan()
        for row in row_numbers:
            for letter in seat_letters:
                passenger = self._seating[row][letter]
                if passenger is not None:
                    yield (passenger, "{}{}".format(row, letter))


class Aircraft:
    def __init__(self, registration, model, num_rows, num_seats_per_row):
        self._registration = registration
        self._model = model
        self._num_rows = num_rows
        self._num_seat_per_row = num_seats_per_row

    def registration(self):
        return self._registration

    def model(self):
        return self._model

    def seating_plan(self):
        return (range(1, self._num_rows + 1),
                "ABCDEFGHJK"[:self._num_seat_per_row])


def make_flight():
    f = Flight("BA758", Aircraft("G-EUPT", "Airbus A319", num_rows=22,
                                 num_seats_per_row=6))
    f.allocate_seat("12A", "Guido van Rossum")
    f.allocate_seat("15F", "Bjorne Stroustrup")
    f.allocate_seat("15E", "Anders Hejlsberg")
    f.allocate_seat("1C", "John McCarthy")
    f.allocate_seat("1D", "Richard Hickey")
    return f


def console_card_printer(passenger, seat, flight_number, aircraft):
    output = "| Name : {0}" \
             "  Flight : {1}" \
             "  Seat: {2}" \
             "  Aircraft : {4}" \
             "  |".format(passenger, flight_number, seat, aircraft)
    banner = "+" + "-" * (len(output) - 2) + "+"
    border = "|" + " " * (len(output) - 2) + "|"
    lines = [banner, border, output, border, banner]
    card = "\n".join(lines)
    print(card)
    print()

if __name__ == "__main__":
    make_flight()._passenger_seats()

如果有人也可以告诉我如何解释错误信息或者以另一种方式使用调试器我会很高兴。

3 个答案:

答案 0 :(得分:0)

试试这个,你有{4}而不是{3}

output = "| Name : {0}" \
         "  Flight : {1}" \
         "  Seat: {2}" \
         "  Aircraft : {3}" \
         "  |".format(passenger, flight_number, seat, aircraft)

答案 1 :(得分:0)

{4}更改为{3},它应该有效。

答案 2 :(得分:0)

output = "| Name : {0}" \
         "  Flight : {1}" \
         "  Seat: {2}" \
         "  Aircraft : {4}" \
         "  |".format(passenger, flight_number, seat, aircraft)

输出格式中输入错误:Aircraft : {4}.format()中只有4个参数,因此没有{4}项。将其更改为{3}