问题
Hello i have dataset a few thousand lines which is split in even and odd number lines and i can't find a way to join them together again in the same line. Reading the file and overwriting it is fine or making a new file.
I have found this example to print the seperate lines but can't get it to write it to file.
I would like it to look like this:
Time = 1 Temperature1 = 24.75 Temperature2 = 22.69 Temperature3 = 20.19 RPM = -60.00
Time = 2 Temperature1 = 24.75 Temperature2 = 22.75 Temperature3 = 20.19 RPM = -60.00
etc...
Example of dataset:
Time = 1 Temperature1 = 24.75 Temperature2 = 22.69 Temperature3 = 20.19
RPM = -60.00
Time = 2 Temperature1 = 24.75 Temperature2 = 22.75 Temperature3 = 20.19
RPM = -60.00
Time = 3 Temperature1 = 24.75 Temperature2 = 22.75 Temperature3 = 20.19
RPM = -60.00
Time = 4 Temperature1 = 24.81 Temperature2 = 22.81 Temperature3 = 20.25
RPM = -60.00
Time = 5 Temperature1 = 24.81 Temperature2 = 22.81 Temperature3 = 20.19
RPM = -60.00
Time = 6 Temperature1 = 24.81 Temperature2 = 22.81 Temperature3 = 20.19
RPM = -60.00
Time = 7 Temperature1 = 24.81 Temperature2 = 22.81 Temperature3 = 20.25
RPM = -60.00
Time = 8 Temperature1 = 24.81 Temperature2 = 22.87 Temperature3 = 20.25
RPM = -60.00
Time = 9 Temperature1 = 24.87 Temperature2 = 22.87 Temperature3 = 20.25
RPM = -60.00
Time = 10 Temperature1 = 24.87 Temperature2 = 22.87 Temperature3 = 20.25
RPM = -60.00
回答1:
You can use %
(modulus) to determine if the line is odd or even. If it's even, then join together the last line and the current line.
# Using your dataset as a string
data_split = data.split("\n")
for i in range(len(data_split)):
if i % 2:
lines = [data_split[i-1], data_split[i]]
print " ".join(lines)
Output:
Time = 1 Temperature1 = 24.75 Temperature2 = 22.69 Temperature3 = 20.19 RPM = -60.00
Time = 2 Temperature1 = 24.75 Temperature2 = 22.75 Temperature3 = 20.19 RPM = -60.00
Time = 3 Temperature1 = 24.75 Temperature2 = 22.75 Temperature3 = 20.19 RPM = -60.00
...
来源:https://stackoverflow.com/questions/39786091/python-join-data-lines-together