[英]Printing inside a for-loop
(抱歉有任何錯誤,英語是我的第二語言,我還在學習)
我試圖在我的吉他熱身和音階練習中自動化一些事情,但在這一點上卡住了。 首先,我編寫了這段代碼來隨機選擇三個手指圖案,並且只有在選擇了所有其他項目后才會再次選擇集合中的所選項目,但在fingerPatternLoop.txt 中什么也沒有,在終端上什么也沒有。
import random
fingerPatterns = set(['1, 2, 3, 4', '1, 2, 4, 3', '1, 3, 4, 2', '1, 3, 2, 4',
'1, 4, 3, 2', '1, 4, 2, 3', '2, 1, 3, 4', '2, 1, 4, 3', '2, 3, 1, 4',
'2, 3, 4, 1', '2, 4, 3, 1', '2, 4, 1, 3', '3, 1, 2, 4', '3, 1, 4, 2',
'3, 2, 4, 1', '3, 2, 1, 4', '3, 4, 2, 1', '3, 4, 1, 2', '4, 1, 2, 3',
'4, 1, 3, 2', '4, 2, 1, 3', '4, 2, 3, 1', '4, 3, 1, 2', '4, 3, 2, 1',
])
fingerPatternLoop = open("fingerPatternLoop.txt", "a+")
rand_warmup = random.sample(fingerPatterns, 3)
for rand_warmup in fingerPatternLoop:
if rand_warmup not in fingerPatternLoop:
print(rand_warmup)
print(f"{rand_warmup}", file=fingerPatternLoop)
刪除 for 循環使代碼工作。
print(rand_warmup)
print(f"{rand_warmup}", file=fingerPatternLoop)
但我仍然無法弄清楚如何讓這些打印在 for 循環中工作,以驗證 random.sample 的任何項目是否已經發生,並在已經選擇了所有 24 個項目的情況下清除了fingerPatternLoop.txt。
文件模式a+
從來沒有用。 你打開文件進行讀寫,最后設置文件指針。 所以閱讀永遠不會進入for循環。
您必須分兩步讀取和寫入文件。
rand_warmup = random.sample(fingerPatterns, 3)
with open("fingerPatternLoop.txt") as lines:
found = rand_warmup in map(str.strip, lines)
if not found:
with open("fingerPatternLoop.txt", "a") as output:
print(rand_warmup, file=output)
FingerpatternLoop 變量是一個文件對象,您必須讀取它並將其內容存儲在一個變量中,例如:
with open('fingerPatterLoop.txt', 'r') as f:
data = f.readlines()
if str(rand_warmup) not in data:
# write to file
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.