为什么在第一行之后迭代不继续?

Why does the iteration not continue after the first row?

提问人:lora hopkins 提问时间:4/4/2023 更新时间:4/5/2023 访问量:22

问:

我正在获取嵌套列表并尝试让它们像这样打印。

输入 [[1,2,3], [4,5], [6,7,8,9]]

输出 1 |2 |3 4 |5 6 |7 |8 |9

user_input= input()
lines = user_input.split(',')
mult_table = [[int(num) for num in line.split()] for line in lines]

for row in mult_table:
    length = len(row)
    i = 0

    while i < length:
        row.insert(i + 1 , ' | ')
        i += 2
    for cell in row:
        print (cell, end='')
    print()

我期望它遍历每个字符串,但实际上,它只遍历第一个字符串。

输出为 1 |2 |3 45 6789

for-loop while-loop 嵌套 嵌套列表

评论


答:

0赞 Pranav 4/5/2023 #1

这是您可以在此处使用的方法之一:

mult_table = [[1,2],[3,4],[2,3,4,5]]

delim = " | "

for row in mult_table:
    print(delim.join(map(str, row)), end = " ")

评论

0赞 lora hopkins 4/6/2023
感谢您的回复。我还没有读过任何关于地图函数的文章,所以我认为这不是我应该采取的方法。还有其他想法吗??我尝试用 end = “ | ” 做类似的事情,除了行尾也有一条垂直线外,它几乎是正确的。