使用Python将特定行转换为列表

2024-03-28 20:47:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着用200行代码把每一组10行转换成自己的列表。在

1
Victorious Boom
834
7
0
7.00
1
0
1.00
1
2
Tier 1 Smurf
806
4
0
4.00
1
0
1.00
1
3
AllHailHypnoToad
754
4
0
4.00
1
0
1.00
1

我想看起来像:

^{pr2}$

任何帮助都将不胜感激


Tags: 代码列表tierboompr2smurfvictoriousallhailhypnotoad
3条回答

这是我的答案。 它需要一个源.txt与逐行类型的数据一起输出到目标.txt文件。我希望这有帮助。在

file  = open("source.txt", "r")
data = []
for line in file:
    data.append(line)
length = len(data)
file.close()

#output file
target = open("target.txt", "w")

#will become a line in the file
item = ""

if length % 10 == 0:
    for y in range(0, length, 10): 
        for x in range(0, 10):
            item += str(data[x + y].strip()) + " "
        target.write(item + "\n")
        item = ""   
else:
    print ("Bad data set. File "+ str(length) + " elements!")
count=0
fixed_list=[]
temp_list=[]
for line in open("some.txt").readlines():
    count+=1
    temp_list.append(line.strip())
    if (count%10)==0:
        fixed_list.append(temp_list)
        temp_list=[]
print fixed_list
full_list = [line.strip() for line in open("filename", 'r')] #read all lines into list
sublist = [full_list[i:i+10] for i in range(0, len(full_list), 10)]  #split them into sublist with 10 lines each

相关问题 更多 >