简体   繁体   中英

How to read this input file in a specific way in Python?

I have an input.txt file here which I need to read in order to use the values in it. The first line three lines are put into three different variables, while the other lines (the ones with 3 values in it) will be placed in three different lists per value. How do I go about this?

0.1
0.5
1
0 0 1
0 1 1
1 0 1
1 1 0

Expected output is for example:

a = 0.1
b = 0.5
c = 1
list1 = [0, 0, 1, 1]
list2 = [0, 1, 0, 1]
list3 = [1, 1, 1, 0]

You can optimize with some for cycles and "one-liners" but here is the solution:

with open('input.txt', 'r') as file:
    data = file.read().splitlines()

a = float(data[0])
b = float(data[1])
c = int(data[2])

r1 = [n.strip() for n in data[3]]
r2 = [n.strip() for n in data[4]]
r3 = [n.strip() for n in data[5]]
r4 = [n.strip() for n in data[6]]

list1 = [int(r1[0]), int(r2[0]), int(r3[0]), int(r4[0])]
list2 = [int(r1[2]), int(r2[2]), int(r3[2]), int(r4[2])]
list3 = [int(r1[4]), int(r2[4]), int(r3[4]), int(r4[4])]

While editing my post, the answered dawned on me I guess

f = open("try.txt")
a = 0
b = 0
c = 0
vars = []
list1 = []
list2 = []
list3 = []
list_digits = [3, 4, 5, 6]
var_spec = [0, 1, 2]

for position, line in enumerate(f):
    if position in list_digits:
        list1.append(int(line.split(' ')[0]))
        list2.append(int(line.split(' ')[1]))
        list3.append(int(line.split(' ')[2]))
    elif position in var_spec:
        vars.append(line)    
f.close
a = vars[0]
b = vars[1]
c = vars[2]

Not the most elegant way I could have done this but I think it is fine

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