Python嵌套循环:打印座椅

2024-05-12 22:13:07 发布

您现在位置:Python中文网/ 问答频道 /正文

给定行和列,打印剧院所有座位的列表。如1A或3E所示,行是编号的,列是字母。在每个座位后(包括最后一个座位后)打印一个空格。 例如:num_rows = 2num_cols = 3打印: 1A 1B 1C 2A 2B 2厘米

num_rows = 2
num_cols = 3
c1 = 1
while c1 <= num_rows:
    c2 = 'A'
    while c2 <= 'C':
        print('%s%s' % (c1, c2), end=' ')
        c2 = chr(ord(c2) + 1)
    c1 += 1
print()

当我使用2行3列或5行3列进行测试时,输出返回正确。但是,当我使用0列进行测试时,它返回“1a1b1c2a 2b2c3a3b3c4a4b4c5a5c5c”,而不返回任何内容。我试着把c2='A'改成c2=num戋cols,但什么也没改。


Tags: 列表字母num编号rows行和列空格print
3条回答
"""    c2 = 'A'
while c2 <= 'C':"""

我想问题就在这里。计算字母表需要一个像“C”一样的赋值,但是如果你想用更多或更少的列遍历字母表,你需要给最大值赋值,而不是给字符赋值。(大写字母分配仅在列介于范围(1,27)之间时才有效)请尝试以下操作:

num_rows = 2
num_cols = 3

rows = 1                       #create a number to start counting from for rows
while rows <= num_rows:        #start iterating through number of rows
    cols = 1                   #create a number to start counting from for columns
    alpha = 'A'                #starting point for alphabet
    while cols <= num_cols:                    #iterates through number of columns
        print('%s%s' % (rows, alpha), end=' ')
        cols +=1                               #number of columns needs to increase
        alpha = chr(ord(alpha) + 1)            #alphabet needs to increase
    rows += 1                                  #number of rows needs to increase
print()                                         

"""This is my very first attempt. Please let me know if my code can be cleaner and more readable"""

我为什么首先想到

import itertools
print(' '.join(''.join(x) for x in itertools.product('12', 'ABC')))

是吗?

您没有使用num_cols,而是使用硬编码列C。您应该根据num_cols设置列的上界。

更改:

while c2 <= 'C':

致:

while c2 < chr(ord('A') + num_cols):

相关问题 更多 >