我写了一些代码,它取了 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 File对象。 默认情况下,python 不会包含换行符,当您写入文件时,您必须自己包含这些换行符。
我还建议对 File 对象使用上下文管理器。
请参阅此代码:
with open("results.txt", 'w') as output:
for i in range(100):
population = range(0, 100)
# TTF = 0 # Nothing is done with this number. Why is it here?
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(f"{results}n") # Assuming you're using Python >= 3.6
如果您使用的是不支持 f 字符串的旧版本的 Python,请将f"{results}n"
替换为"{0}n".format(results)