【问题标题】:How would I incorporate more than one for loop?我将如何合并多个 for 循环?
【发布时间】: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)])

标签: python arrays for-loop


【解决方案1】:

不需要额外的 for 循环

只需检查row_index == col_index 的条件,如果是,则将! 添加到字符串中。

for row_index in range(5):
    row = ''
    for col_index in range(5):
        if row_index == col_index :
              row+= '!'
        else :
              row += ' - '
    print(row)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    • 2012-09-02
    • 2020-11-17
    • 2021-10-08
    相关资源
    最近更新 更多