简体   繁体   中英

How can I loop through a textfile but do something different on the first line, Python

I have a text file that looks something like this :

 original--                 expected output--
0 1 2 3 4 5              SET : {0,1,2,3,4,5}
1 3                      RELATION:{(1,3),(3,1),(5,4),(4,5)}
3 1 
5 4                      REFLEXIVE : NO
4 5                      SYMMETRIC : YES

and part of the code is having it print out the first line in curly braces, and the rest within one giant curly braces and each binary set in parentheses. I am still a beginner but I wanted to know if there is some way in python to make one loop that treats the first line differently than the rest?

try this with filename is your file ..

with open("filename.txt", "r") as file:
    set_firstline = []
    first_string = file.readline()
    list_of_first_string = list(first_string)
    for i in range(len(list_of_first_string)):
        if str(i) in first_string:
            set_firstline.append(i)
    
    print(set_firstline)
OUTPUT : [0,1,2,3,4,5]

im new as well. so hope I can help you

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