【发布时间】: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