[英]How to shuffle the contents of a text file in groups of n lines in Python
假设文本文件是这样的:
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]))
您可以使用任何推荐的分块方法来生成组。 对于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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.