【问题标题】:Python while loop iteration does not workPython while循环迭代不起作用
【发布时间】:2017-07-05 00:57:19
【问题描述】:

我是 Python 编程的新手,几个小时没能解决以下问题。我有包含四行的示例文件。我希望在文件行中找到用户的两个输入,但是我的循环似乎没有遍历所有行。这是文件的内容,元素用空格分隔:

Google 1 2  
Apple 13 17  
Microsoft 22 8  
Verizon 6 15

这是我的代码:

import sys
with open('manylines.txt','r') as myfile:
    results = [line.split() for line in myfile]

    for i in results:
        print(i)


        term1=input("Enter the first term:")
        while  term1 not in i :
            print("Term not found,please try again:")
            term1 = input("Enter the first term:")

        term2 = input("Enter the second term:")
        while term2 not in (i) :
            print("Term not found,please try again:")
            term2 = input("Enter the second term:")
        print(i)
        print(i)
        sys.exit()

我希望输入例如 Google 和 Microsoft 并获得以下输出:

['Google','1','2']  
['Microsoft','22','8']

作为两个列表。但是,我的代码只找到第一行而不是其他行。你能告诉我为什么它不迭代其他行吗?如何解决这个问题?提前致谢!

【问题讨论】:

  • 第一学期和第二学期的价值观是什么?
  • 您在 for 循环中调用 sys.exit,因此程序将始终在第一次迭代时终止。
  • 值例如 Google 和 Microsoft @lmiuelvargasf
  • 试试result = [line.split() for line in myfile.readlines()]
  • 当我删除 sys.exit() @juanpa.arrivillaga 时同样的事情

标签: python for-loop while-loop user-input lis


【解决方案1】:

这里的代码不会从您的尝试大幅更改...它利用lower()title() 允许用户输入的各种大写:

import sys

with open('data.txt','r') as f:
    results = [line.split() for line in f]

while True:
    found = False
    term = input("Enter a company to search or type exit: ")
    if term.lower() == "exit":
        break
    for record in results:
        if record[0] == term.title():
            print(record)
            found = True
            break
    if not found:
        print("Term not found, please try again...")

print("Goodbye!")
sys.exit(0)

示例用法:

Enter a company to search or type exit: Google
['Google', '1', '2']
Enter a company to search or type exit: microsoft
['Microsoft', '22', '8']
Enter a company to search or type exit: Amazon
Term not found, please try again...
Enter a company to search or type exit: Exit
Goodbye!

您只能提示用户输入“两个术语”:

out1, out2 = [], []
term_count = 1
while term_count < 3:
    found = False
    term = input("Enter term %d or type exit: " % term_count)
    if term.lower() == "exit":
        break
    for record in results:
        if term_count == 1 and record[0] == term.title():
            print(record)
            out1 = list(record)
            found = True
            term_count += 1
            break
        if term_count == 2 and record[0] == term.title():
            print(record)
            out2 = list(record)
            found = True
            term_count += 1
            break
    if not found:
        print("Term not found, please try again...")

示例用法:

Enter term 1 or type exit: Amazon
Term not found, please try again...
Enter term 1 or type exit: Google
['Google', '1', '2']
Enter term 2 or type exit: Microsoft
['Microsoft', '22', '8']
Goodbye!

【讨论】:

  • 非常感谢@shash678。我还想问一件事。我希望只提示两个输入,如我的代码所示。你能告诉我怎么做吗?我的意思是,有一次它检查两个输入,当它得到这两个找到的项目时,它会打印这两个适当的列表,就像你显示的那样,程序退出。你能显示这个吗?
  • 谢谢@shash678。我想问的最后一件事。这大约是我要寻找的,但是否有可能,我为它们分配了两个变量。我的意思是如果 Google 找到了,将输出 ['Google', '1', '2'] 分配给 out1,并将 Microsoft 输出 ['Microsoft', '22', '8'] 分配给 out2。我的意思是我想将它们作为两个列表,然后将这些列表用于程序的其他部分以用于进一步的目的。怎么可能做到?非常感谢您的大力帮助!
  • @python_beginner 你去编辑了你的规范的第二个代码块,现在你可以在任何你想要的地方使用 out1 和 out2 :) 如果你觉得我的回答有帮助,请考虑将我的答案标记为正确 :) –
  • 完美,是的,实际上,我明白了。感谢您的大力帮助。标记为最佳答案。
【解决方案2】:

试试下面的代码。此代码标识找到了哪个术语并询问未找到的术语。

你没有正确地制作你的循环。当您的循环第一次执行时,它有 Google,term1 包含 Google,term2 包含 Microsoft。因此它会打印 Google,然后您就可以使用 sys.exit() 停止执行。所以当然它会打印第一行而不是其他行。

import sys
with open('tempa.txt','r') as myfile:
    results = [line.split() for line in myfile]

NeedToExecute = 0
term1 = False
term2 = False

list1 = None
list2 = None

while NeedToExecute != 2:

    if(term1 != True):
        term1 = input("Enter the first term:")

    if(term2 != True):
        term2 = input("Enter the second term:")

    for i in results:

        if term1 in i :
            NeedToExecute = NeedToExecute + 1
            term1 = True
            list1 = i
            print(i)

        if term2 in i :
            NeedToExecute = NeedToExecute + 1
            term2 = True
            list2 = i
            print(i)

print list1
print list2

【讨论】:

  • 感谢@Ujjaval Moradiya 的回答。但是你能告诉我如何为这两个列表分配两个变量吗?假设第一个成为 list1,第二个是 list2。我希望在我的程序中将这些列表用于进一步的目的。非常感谢您的帮助!
  • 是的,你可以这样做。你怎么不这么想。这并不难。检查我更新的代码
  • 是的,我明白了,定义列表,然后在那里添加结果。非常感谢您的大力帮助!
猜你喜欢
  • 2014-01-12
  • 1970-01-01
  • 2017-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-09
  • 2011-10-19
  • 1970-01-01
相关资源
最近更新 更多