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

I am writing a program that reads a 2D list from a .txt file, and I'm trying to loop through the list, and print each item in it. I've used a for loop to loop through each item in the list. The contents of the 2D list in the .txt file is:

['1', '10']

['Hello', 'World']

This is my code so far for opening the file, reading it, and looping through each item in the list:

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

file_contents = file.read()

for i in file_contents.split():

print(i)

file.close()

The output that I get from this for loop is:

['1',

'10']

['Hello',

'World']

However, the output that I'm trying to get is:

1 10

Hello World

Is there any way that I can get this output? I'm not sure how to remove the square brackets, commas and quotation marks. And once that is done, I can't figure out how to format the lines so that they are displayed as they appear in the external file (with the tabs between each item). I'm quite new to Python, so any suggestions would be great!

解决方案

Splitting on newlines and outputting in your format:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值