python - 保存多个洗牌的 csv 文件
问题描述
有没有一种快速的方法可以将列表洗牌 n 次(以不同的顺序)并将其保存为 n 个单个 csv 文件?我已经搜索了很多,但找不到任何关于它的东西。我有以下代码,但我确信它可能会更短,因此我不能确定所有洗牌列表都有不同的顺序。有人有解决方案吗?
import random
example = ['S01_a', 'S01_b', 'S02_a', 'S02_b', 'S03_a', 'S03_b', 'S04_a']
while True:
example
shuffle3 = []
last = ""
while example:
i = example
if last:
i = [x for x in i if x[4] != last[4]]
if not i:
#no valid solution
break
newEl = random.choice(i)
last = newEl
shuffle3.append(newEl)
example.remove(newEl)
if not example:
break
fid = open("example.csv", encoding='latin1', mode="w")
fid.writelines(shuffle3)
fid.close()
解决方案
您可以在列表索引上生成所有可能的排列,然后按照排列给出的顺序选择元素以生成新的打乱列表。最后,打乱列表列表并选择第一个 N。
from itertools import permutations
from random import shuffle
example = ['S01_a', 'S01_b', 'S02_a', 'S02_b', 'S03_a', 'S03_b', 'S04_a']
indices = [x for x in range(0,len(example))]
n_perm = 5
all_permutations = list(set(permutations(indices)))
shuffle(all_permutations)
my_permutations = all_permutations[:n_perm]
for index, elem in enumerate(my_permutations):
new_shuffle = [example[x] for x in elem]
with open("example_{}.csv".format(str(index)), "w") as fid:
fid.writelines(",".join(new_shuffle))
推荐阅读
- typescript - Typescript:你能根据参数对象中单个键的值获取函数的返回类型吗?
- amazon-web-services - aws cli 没有在一个配置文件的源配置文件中找到区域,但可以与另一个配置文件一起使用
- javascript - 在javascript中将纯文本转换为模板文字
- python - 如何在 tkinter 中逐行插入文本?
- powershell - 为什么 PowerShell 不处理这个 $?正确退出代码?
- javascript - react-router中的路径和url有什么区别
- c++ - 评估多位表达式
- flutter - 错误:无法确定任务 ':app:compileDebugJavaWithJavac' 的依赖关系。尝试启动应用程序时
- python-xarray - 如何计算 xarray 中的完整外积(协方差)?
- react-native - react native usememo renderitem 为什么不起作用?