#python #list #output #modulo
#python #Список #вывод #modulo
Вопрос:
Мне удалось заставить мою программу распечатать схему размещения тележки поезда аналогично тому, что я хочу, но в спецификации программы говорится, что схема размещения должна быть распечатана другим способом (см. Внизу). Код выглядит следующим образом:
while i <= rows:
j = 1
i = 1
while j <= seats:
k = j (4*(i-1))
field.append("{}".format(k)) #Adds the two values to one.
j = 1
i = 1
a = 1
b = 1
for isle in range(rows):
for column in range(seats):
if a == 13:
print(" ↓ TYST AVD ↓")
if a % 4 != 0:
print(field[a-1].ljust(4), end='')
else:
print(field[a-1].ljust(4), end='' "n")
a = 1
b = 1
Это выводит:
1 2 3 4
5 6 7 8
9 10 11 12
↓ TYST AVD ↓
13 14 15 16
17 18 19 20
21 22 23 24
Моя проблема заключается в том, чтобы поменять местами все остальные строки, т. Е. Я хочу это:
1 2 3 4
8 7 6 5
9 10 11 12
↓ TYST AVD ↓
16 15 14 13
17 18 19 20
24 23 22 21
Я пытался реализовать modulo несколькими различными способами или нарезать список — который изменяет только порядок чисел (например, 24 становится 42) — но, похоже, я ничего не могу заставить работать. Возможно ли это сделать с помощью modulo или нарезки, или мне нужно переосмыслить свой подход к этой задаче?
Комментарии:
1. Почему вы бы использовали
modulo
?l[::-1]
вернет обратноеl
.
Ответ №1:
Вот решение вашей проблемы. Не стесняйтесь играть с параметрами строк / столбцов, чтобы изменить вывод.
from math import floor
# The parameters of seating-plan
rows = 6
columns = 4
# Create the range of seat-numbers,
# and then "chunk" them up according to columns
seat_rows = [i for i in range(1, rows*columns 1)]
seat_rows = [seat_rows[i:i columns] for i in range(0, len(seat_rows), columns)]
for idx, row in enumerate(seat_rows):
# print out the indicator for the "Silent Aisles"
# with a bias toward silent seats.
if idx == floor(len(seat_rows) / 2):
# Format Explanation:
# ^ = center text
# (len(row)*4)-2 = provides the width of the row to center,
# and centers it inside of that multiple of the width (-2).
print("{:^{}}".format('↓ TYST AVD ↓', (len(row)*4)-2))
# If idx is uneaven, then reverse the row.
if idx % 2 == 1:
row = row[::-1]
# Creates a format-string for each entry in row
# Format Explanation:
# < = aligns the text to the left
print(("{:<4}"*len(row)).format(*row))
Вывод:
1 2 3 4
8 7 6 5
9 10 11 12
↓ TYST AVD ↓
16 15 14 13
17 18 19 20
24 23 22 21