python - 如何在 Python 中以 n 行为一组随机排列文本文件的内容

标签 python file

假设文本文件是这样的:

1
2
3
4
5 
6
...

我想要的是以 N 行为一组随机排列内容,而不打乱每组中的行,如下所示:

#In this case, N = 2.
5
6
1
2
7
8
...

我的文件不大,肯定不会超过 50 行。

我已经尝试使用这段代码来做到这一点:

import random


with open("data.txt", "r") as file:
    lines = []
    groups = []
    for line in file:
        lines.append(line[:-1])
        if len(lines) > 3:
            groups.append(lines)


            lines = []

    random.shuffle(groups)


with open("data.txt", "w") as file:
    file.write("\n".join(groups))

但是我得到这个错误:

Traceback (most recent call last):
  File "C:/PYTHON/python/Data.py", line 19, in <module>
    file.write("\n".join(groups))
TypeError: sequence item 0: expected str instance, list found

有更简单的方法吗?

最佳答案

您尝试加入列表列表;先把它们弄平:

with open("data.txt", "w") as file:
    file.write("\n".join(['\n'.join(g) for g in groups]))

您可以使用 recommended methods of chunking 中的任何一个产生你的组。使用 file 对象,您需要做的就是 zip() 文件本身:

with open("data.txt", "r") as file:
    groups = list(zip(file, file))

请注意,如果文件中的行数为奇数,这将删除最后一行。这包括现在的换行符,所以加入 '' 而不是 '\n'

您还可以在洗牌之前将每组的两条线连接在一起:

with open("data.txt", "r") as file:
    groups = [a + b for a, b in zip(file, file)]

random.shuffle(groups)

with open("data.txt", "w") as file:
    file.write("".join(groups))

关于python - 如何在 Python 中以 n 行为一组随机排列文本文件的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46754592/

相关文章:

python - 带有类型推导的 swig python 模板函数

c++ - Linux 配置文件库

c# - 使用 MVC 3 上传文件

python - 我的装饰器适用于常规功能,但不适用于实例

c - 在文件中搜索字符串

php - 长时间运行的 Golang 程序和资源(文件句柄、tcp 连接等)

function - 如何使用 Jodit 编辑器正确插入上传的图片?

python - defaultdict的含义(lambda : defaultdict(dict))

python - 如何让计时器更有效率

python - GeoJSON 数据不包含有意义的数据 GeoDjango