输出重复

时间:2018-05-14 13:35:23

标签: python python-2.7

由于我的输出已被复制,我遇到了一个问题。

我有点想知道为什么它会重复它的方式,但我不知道问题是如何造成的。

目前输出重复3(数组gen_coms包含的值的数量。

以下代码片段与此问题有关(请忽略代码中的所有注释):

第一个功能:

 gen_coms = []
    def getCommands():
        for file in os.listdir(com_dir):
            if file.endswith(com_ext):
                global gen_coms
                a = gen_coms.append(file[:-len(com_ext)]) # Looks good however formats output as ['a','b','c'] is there a way to format it as 'a','b','c' or a,b,c ?

第二个功能:

def genTerm():
while True:
    gin = raw_input('> ')
    for commands in gen_coms: # Prints out 3 vars. This didn't happen before but I am assuming thats because gen_coms now technically has a value of 3?
        if gin in gen_coms:
            print gin
        else:
            print('Unrecognized command!')

示例输入/输出,以帮助显示我得到的问题:

> a # This is the input -> a
a  # Here down is output
a
a

输入输入a并且仅打印正确的输出,而不是我预期的单次时间。这不仅限于a但每一个输出。

非重要的附注:

很抱歉,如果这个问题的格式不是最好的,那么由于睡眠不足,我现在非常难以集中精力思考,并会进行编辑纠正语法,拼写和整体一两分钟的布局。

还要感谢你花时间阅读这篇冗长且极有可能重复的问题。

2 个答案:

答案 0 :(得分:1)

def genTerm():
    while True:
          gin = raw_input('> ')
          for commands in gen_coms: 
              if gin in gen_coms:
                 print gin
              else:
                 print('Unrecognized command!')

这种情况正在发生,因为实际上是第4行广告第5行 让我解释一下,因为gen_coms长度是3,循环在这里运行三次,并且在for循环的每次迭代中如果条件变为真,并且每次都打印第一个字符。

所以,打印 a 三次;

第五行中的

用命令替换gen_coms。

答案 1 :(得分:0)

在查看发布的评论并查看我的代码之后,我找到了一个修复:

def genTerm():
    while True:
        gin = raw_input('> ')
        if gin in gen_coms:
            print gin
        else:
            print("Invalid command!")

这解决了我的问题,并缩短了功能。感谢所有花时间研究这个问题的人。