Python 循环和while循环函数的“TypeError:应为字符缓冲区对象”
我已经写了一些代码,它从100个数字中抽取样本,然后随机抽取样本来增加数字列表,然后将它们随机减少到100 我在计算循环中的迭代次数,列表中的所有数字都是相同的Python 循环和while循环函数的“TypeError:应为字符缓冲区对象”,python,Python,我已经写了一些代码,它从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.rando
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默认不包含换行符,您必须自己包含这些换行符 我还建议对文件对象使用上下文管理器 请参阅此代码:
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-string的较旧版本的Python,请将f{results}\n替换为{0}\n.formatresults我使用的是Python 2.7,因此感谢您的澄清