代码:
x = ['1', '2', '3']
y = ['a', 'b', 'c']
rangeend = len(x)
for i in range(0, rangeend):
with open("file20.txt") as f:
for line in f:
count = 0
line = line.strip()
z = line.split(" ")
if z[0] == x[i] :
count = 1
a = z[0], z[1]
b = x[i],y[i]
if a == b:
print "ok"
break
else:
print "Failed"
break
if count != 1:
print "{} not found".format(x[i])
file20.txt:
1 a
2 b
5 c
x
列表包含3
但file20.txt
在行的开头没有3
(第一个字符串)
我想要打印的是文件中的3 not found
,并且最后只需要打印一次。
注意:不仅元素3
,x
列表中的任何元素,但file20.txt
文件行在开头没有(第一个字符串)。我想要找不到印刷品。
下面是代码输出,2
实际存在,但它正在打印2 not found
(实际上它不会打印2 not found
)3
不在file20.txt
中1}}但打印3 not found
是正确的,但问题是打印3次。我只想让它打印3 not found
,只打一次。
0
('1', 'a') ('1', 'a')
ok
1
2 not found
('2', 'b') ('2', 'b')
ok
2
3 not found
3 not found
3 not found
答案 0 :(得分:0)
将if count != 1
块移到内部for
循环之外看起来像是在工作。你试过了吗?
x = ['1', '2', '3', '4']
y = ['a','b','c','d']
rangeend = len(x)
for i in range(0, rangeend):
with open("bob.txt") as f:
for line in f:
count = 0
line = line.strip()
z = line.split(" ")
if z[0] == x[i] :
count = 1
a = z[0], z[1]
b = x[i], y[i]
if a == b:
print "ok"
break
else:
print "Failed"
break
if count != 1:
print "{} not found".format(x[i])