【发布时间】:2017-09-22 02:10:24
【问题描述】:
我最近开始学习 python,想知道是否可以帮助我开发一个包含多个 for 循环的数组。
''' Postcondition: A 5x5 array as follows is on the monitor:
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
'''
for row_index in range(5):
row = ''
for col_index in range(5):
row += ' - '
print(row)
现在我正在尝试制作类似的东西,但这次有一个额外的循环。
'''Postcondition: A 5x5 array as follows is on the monitor:
! - - - -
- ! - - -
- - ! - -
- - - ! -
- - - - !
'''
我将如何添加一个额外的 for 循环来获得这个结果?
【问题讨论】:
-
检查
col_index何时等于row_index,然后添加!而不是 - -
值得注意的是,您可以将其生成为嵌套列表组合。
'\n'.join([' '.join(['!' if x==y else '-' for x in range(5)]) for y in range(5)])