Python stdout 和 for 循环不会打印列表中的第一个元素(第二个元素替换第一个))

Python stdout and for loop won't print the first element in a list (Second element replaces the first))

我正在创建一个程序,让用户输入一个列表,然后从该列表生成一个 table。该列表中的元素(对于 new_table 函数)将成为列的标签。

from sys import stdout

def new_table(columns):
    for i in columns:
        length = len(i)
        stdout.write('-' * (length + 8))
    print('\r')
    for x in columns:
        stdout.write('|   ' + i + '   |')

new_table(['Animal', 'Danger'])

但是,当我 运行 程序时,不是将列表的两个元素都显示为列 titles/labels 它只显示两个标题的第二个(第二个元素替换第一个) :

----------------------------
|   Danger   ||   Danger   |

我希望它像这样显示:

----------------------------
|   Animal   ||   Danger   |

感谢您的帮助和建议。

一致性有帮助。您使用 x 循环但使用 i.