Python:每第n行拆分后的换行符

时间:2016-08-28 00:36:05

标签: python

我想在python中的txt文件中每10个数字或9个9分割后强制换行?我该怎么做?所以说我有

Input would be something like: 
40 20 30 50 40 40 40 40 40 40  
20 40 20 30 50 40 40 40 
20 40 20 30 50 40 40 40 40 20 20 20
20 20 20 

int txt.file    输出应该是

40 20 30 50 40 40 40 40 40 40  
20 40 20 30 50 40 40 40 
20 40 20 30 50 40 40 40 40 20
20 20 
20 20 20 

所以基本上在每10个数字或9行分割后中断

我试过了:

with open('practice.txt') as f:

    for line in f:
         int_list = [int(num) for num in line.split() ]
         if len(int_list) < 20:
            print(int_list)
         else: 

             new_list = int_list[20:]
             int_list = int_list[:20]
             print(int_list)
             print(new_list)

但这并不能解决它。另请注意,线长可以变化。所以第一行可以有5个数字,第二行有9个,第三行有10个,第四个有10个

2 个答案:

答案 0 :(得分:2)

看起来with语句下面的所有内容都应缩进一个级别。您的方法似乎是一个良好的开端,但如果一行中有超过2个组,它将无法工作。以下代码负责处理并简化了一些事情:

with open('practice.txt') as f:
    values = []
    for line in f:
        int_list = [int(num) for num in line.split()]
        # the next line splits int_list into groups of 10 items, 
        # and appends all the groups to the values list
        values.extend(int_list[i:i+10] for i in range(0, len(int_list), 10))

print values
# [
#     [40, 20, 30, 50, 40, 40, 40, 40, 40, 40],
#     [20, 40, 20, 30, 50, 40, 40, 40],
#     [20, 40, 20, 30, 50, 40, 40, 40, 40, 20],
#     [20, 20],
#     [20, 20, 20]
# ]

答案 1 :(得分:0)

如何使用[count]计算列表中项目的出现次数?

list == [40, 20, 30, 50, 40, 40, 40, 40, 40, 40, 20]
for i in list:
    if list.count(i) > 10:
        # Do Stuff