Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在for循环中打印_Python_For Loop_If Statement_Printing - Fatal编程技术网

Python 在for循环中打印

Python 在for循环中打印,python,for-loop,if-statement,printing,Python,For Loop,If Statement,Printing,对不起,我犯了错误,英语是我的第二语言,我还在学习 我试图在我的吉他热身和音阶练习中自动化一些东西,但在这一点上陷入了困境。 首先,我编写了这段代码来随机选择三个手指模式,并且只有在选择了所有其他项目之后,才会再次选择集合中所选的项目,但是fingerPatternLoop.txt中没有任何内容,terminal中也没有任何内容 import random fingerPatterns = set(['1, 2, 3, 4', '1, 2, 4, 3', '1, 3, 4, 2', '1, 3

对不起,我犯了错误,英语是我的第二语言,我还在学习

我试图在我的吉他热身和音阶练习中自动化一些东西,但在这一点上陷入了困境。 首先,我编写了这段代码来随机选择三个手指模式,并且只有在选择了所有其他项目之后,才会再次选择集合中所选的项目,但是fingerPatternLoop.txt中没有任何内容,terminal中也没有任何内容

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。

fingerPatternLoop变量是一个文件对象,您必须读取它并将其内容存储在一个变量中,例如:

with open('fingerPatterLoop.txt', 'r') as f:
    data = f.readlines()

if str(rand_warmup) not in data:
    # write to file
文件模式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)

你只是在allI使用了不好的变量,我意识到我在问题中使用了错误的标题,我的问题是打印语句在循环中不起作用。无论如何,我将尝试实现你的答案,看看它是否使循环工作。