繁体   English   中英

在 for 循环内打印

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM