Calculate the python target line and the next line

Asked 2 years ago, Updated 2 years ago, 17 views

data
a 100 200
b 250 400
c600 1200


when you have this kind of data Put "a 100 200" in line 1 and "b 250 400" in line 2 in the list and
I want to empty the list after calculating "a-b:50 (250-200)."

What should I do?

I put it on the list using readline, but I don't know how to specify the next line.
Please give me some advice.

python

2022-09-30 19:22

1 Answers

Perhaps you would like to get the next line of the specified line with the for statement.
I feel like I want to display b-a instead of a-b, but the sample code will output according to the question.

If you put it in the list using readline, you can get the next line by specifying the next index of the specified line, such as `list[i+1] for the list variable.

Memory usage increases, but you can also use the zip function to loop lines n and n+1 in parallel.

The clear() function is provided to empty the list.

I think it's a snakefoot (and the code is dirty), but you can automatically calculate the difference by using concat, shift of pandas.

importos

file_name = "data" 
# Preparation (Test File Creation)
with open(file_name, "w") asf:
    f.write("a 100 200\nb 250 400\nc 600 1200")

list = [ ]
with open(file_name, "r") asf:
    print(u "List with for statement")
    for line inf:
        ss=line[:-1].split("")
        list.append(ss)

    print(u "Use index of list")
    size=len(list)
    for i in range (size-1):
        c,n=list[i],list[i+1]#current,next
        print("{}-{}:{}({}-{})".format(c[0], n[0], int(n[1])-int(c[2]), n[1], c[2]))

    print(u "zip the list")
    for c, n in zip (list[:-1], list[1:]):
        print("{}-{}:{}({}-{})".format(c[0], n[0], int(n[1])-int(c[2]), n[1], c[2]))

print(u "empty list")
list.clear()
print(list)

# If there is no pandas in it, remove the bottom from here and run it.
print(u "Use pandas")
import pandas aspd

df=pd.read_csv(file_name, header=None, delimiter="\s+")
ct=pd.concat([df, df.shift(), df-df.shift().shift(-1,axis=1)],axis=1)
for direct[1:].iterrows():
    t, v1, v2 = r[1][0], r[1][1], r[1][2]
    print("{}-{}:{}({}-{})".format(t.iat[1], t.iat[0], int(v1.iat[2]), int(v1.iat[0]), int(v2.iat[1])))


2022-09-30 19:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.