![](/img/trans.png)
[英]Python Function that prints the number of words in a txt file and prints the first 10 words
[英]Write to txt only prints first result of function
我已經編寫了此函數,該函數比較list的元素,在打印到終端時返回正確的結果
def check(samples_avg):
count = 0
for i in range(len(samples_avg)):
for j in range(i + 1, len(samples_avg)):
if (np.any(samples_avg[i]) >= np.all(samples_avg[j] * 5)):
count = count + 1
if (count == len(samples_avg) - 1):
return (True)
else:
return (False)
但是,我希望將完整結果寫入.txt文件。 我創建並打開一個.txt文件,但是只寫入第一個結果False
和其他內容。 我已經嘗試過使用循環的其他一些解決方案,但是它們寫的是None
output = check(samples_avg)
file = open("sample.txt","w+")
file.write(str(output))
file.close()
任何建議或幫助,將不勝感激! 謝謝!
該函數將僅返回找到的第一個返回。 如果要返回所有值,則可以創建一個列表,附加每個結果,然后將其寫入文件中。 像這樣:
def check(samples_avg):
count = 0
results = []
for i in range(len(samples_avg)):
for j in range(i + 1, len(samples_avg)):
if (np.any(samples_avg[i]) >= np.all(samples_avg[j] * 5)):
count = count + 1
results.append(count == len(samples_avg) - 1)
return results
output = check(samples_avg)
file = open("sample.txt","w+")
file.write("\n".join(map(str, output)))
file.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.