我已经写了一些代码,它从100个数字中抽取样本,然后随机抽取样本来增加数字列表,然后将它们随机减少到100
我在计算循环中的迭代次数,列表中的所有数字都是相同的
output = open("results.txt", 'w')
for i in range(100):
population = range(0, 100)
TTF = 0
while len(set(population)) != 1:
scalingfactor = np.random.poisson(5, 100)
sample = np.repeat(population, scalingfactor)
decrease-to-ten = np.random.choice(sample, 100)
population = decrease-to-ten
results += 1
output.write(str(results))
我试图将数字作为列表输出到文本文件中,但我无法管理它
output.write(str(results))
这让我把所有的数字组合成一个长长的数字串
output.write(TTF)
给我这个错误:
TypeError: expected a character buffer object
无论如何,您只能将字符缓冲区写入python文件对象。当您写入文件时,python默认不包含换行符,您必须自己包含这些换行符
我还建议对文件对象使用上下文管理器
请参阅此代码:
如果您使用的是不支持f-string的较旧版本的Python,请将
f"{results}\n"
替换为"{0}\n".format(results)
相关问题 更多 >
编程相关推荐