gpt4 book ai didi

python-3.x - 使用 for 循环从 Python 中的外部文件打印列表的每个项目

转载 作者:行者123 更新时间:2023-12-01 13:21:09 24 4
gpt4 key购买 nike

我正在编写一个从 .txt 文件中读取二维列表的程序,我正在尝试遍历该列表,并打印其中的每个项目。我使用 for 循环遍历列表中的每个项目。 .txt文件中二维列表的内容为:

['1', '10']
['Hello', 'World']

到目前为止,这是我打开文件、读取文件并循环遍历列表中每个项目的代码:

file = open('Original_List.txt', 'r')

file_contents = file.read()

for i in file_contents.split():
print(i)

file.close()

我从这个 for 循环中得到的输出是:

['1',
'10']
['Hello',
'World']

但是,我试图获得的输出是:

1       10
Hello World

有什么方法可以得到这个输出吗?我不确定如何删除方括号、逗号和引号。完成后,我无法弄清楚如何格式化这些行,以便它们显示在外部文件中(每个项目之间有标签)。我是 Python 的新手,所以任何建议都会很棒!

最佳答案

拆分换行符并以您的格式输出:

from ast import literal_eval

file_contents = file.readlines() #read the file as lines
for line in file_contents:
l = literal_eval(line) #convert the string to a list
print(''.join([v.ljust(10, ' ') for v in l])) #left justify and print

关于python-3.x - 使用 for 循环从 Python 中的外部文件打印列表的每个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49910255/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com