简体   繁体   中英

python print eliminate more times printing to output

Code:

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 list has 3 but file20.txt does not have 3 at the begin of the line (first string)

What I am trying is I want to print is, 3 not found in the file and print has to be done only once at the end.

Note: not only element 3 , any element if x list has but file20.txt file line does not have at the begin (first string). I want print does not found.

Below is the code output and 2 is actually present but it is printing 2 not found (Actually it does not print 2 not found ) and 3 is not there in file20.txt but it is printing 3 not found that is correct but the problem is it is printing 3 times. I just want it to print 3 not found , only once.

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  

Moving the if count != 1 block outside the inner for loop looks like working. Have you tried that!

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM