我可以使用模数来反转输出线吗?

Can I use modulo to reverse output lines?

我已经设法让我的程序打印出与我想要的类似的火车车厢座位表,但程序的规范说明应该以不同的方式打印座位表(请参阅底部)。代码如下所示:

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

我试过以几种不同的方式实现模数,或者对列表进行切片 - 这只会改变数字的顺序(例如,它使 24 变成 42) - 但我似乎无法让任何东西发挥作用.这是否与模数或切片有关,或者我是否必须重新考虑我应对这一挑战的方法?

这是您的问题的解决方案。随意使用 rows/columns 参数来更改输出。

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