简体   繁体   English

在 for 循环内打印

[英]Printing inside a for-loop

(Sorry for any mistakes, english is my second language and I'm still learning) (抱歉有任何错误,英语是我的第二语言,我还在学习)

I'm trying to automate some things in my guitar warmups and scales practice and got stuck at this point.我试图在我的吉他热身和音阶练习中自动化一些事情,但在这一点上卡住了。 First I wrote this code to randomly select three finger patterns and that the chosen items in the set would be selected again only after all the other items be chosen, but got nothing in fingerPatternLoop.txt and nothing at terminal.首先,我编写了这段代码来随机选择三个手指图案,并且只有在选择了所有其他项目后才会再次选择集合中的所选项目,但在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)

Removing the for loop made the code work.删除 for 循环使代码工作。

print(rand_warmup)
print(f"{rand_warmup}", file=fingerPatternLoop)

But I still can't figure out how to make those prints work inside a for loop that verify if any of the items of the random.sample already occurred and clear the fingerPatternLoop.txt in the case of all 24 items already been chosen.但我仍然无法弄清楚如何让这些打印在 for 循环中工作,以验证 random.sample 的任何项目是否已经发生,并在已经选择了所有 24 个项目的情况下清除了fingerPatternLoop.txt。

The filemode a+ is never useful.文件模式a+从来没有用。 You open the file for reading and writing, setting the filepointer at the end.你打开文件进行读写,最后设置文件指针。 So reading never enters the for loop.所以阅读永远不会进入for循环。

You have to read and write the file in two steps.您必须分两步读取和写入文件。

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)

The fingerpatternLoop variable is a file object, you have to read it and store its content in a variable, like with: 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