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

标签 python-3.x list for-loop

我正在编写一个从 .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/

相关文章:

python - with ... : for . .. : 在一行中

python - Zip 作为列表理解

python - 如何根据前一行通过逐行计算改进 DataFrame 上的 for 循环?

java - 一个 for 循环中有 2 个计数器?

c# - 通过 for 循环迭代文本框

python-3.x - Anaconda/Orange3 产生 OSError : [WinError 193] %1 is not a valid Win32 application

python - 访问lru_cache的缓存

java - Selenium 使用太多内存

一次添加更多元素的Python列表理解

c# - 如何通过不声明其设置属性来制作只读 C# 列表