Difference in String

Hi,
I have a string as follows

76.21
76.83
77.50
78.50


I need to find out the difference of each of them consecutively. Means i need 76.83-76.21 , 77.50-76.83 , 78.50-77.50 like that. I can not split these numbers individually.
Could anyone please help

Thank you.

Why can’t you?

We need to be clear on how your string object is formatted.

Is it like this…

76.21, 76.83, 77.50, 78.50

or this…

76.21 76.83 77.50 78.50

or this…

76.21
76.83
77.50
78.50

or something else?

In any case, you’ll maybe want to use the .split() method so that you have a list of numbers with which to work.

In my code i am trying to read all the numbers one by one. But the code is not giving the correct result. I am trying to put them in list . But the list file appears to be [l1],[l2],[l3],[l4]. I am trying to get the list in the form [l1,l2,l3,l4].

The last one .
76.21
76.83
77.50
78.50
The .split method is not giving the output. It is giving all the numbers together.

We can’t help you debug your code unless you post it here. Wrap it in three backticks (```, to the left of 1 on a US keyboard) to format it.

So, you’re reading these numbers from a saved file, right?

yes. I extracted those numbers by reading some other file and saved them in a file.

The code is here.

import numpy as np
from collections import defaultdict
import matplotlib.pyplot as plt
import re

def main():

  

 
  with open(r'C:\Users\sarad\ss4.dat.log','r') as line: 
    table = defaultdict(dict)
    for line in line:
      if line:
        entry = line.strip()
        if ':' in entry:
            t = entry
        else:
             if line.startswith("Sensor"):
               _, sample,data = entry.split()
               table[t].update({sample:float(data)})
               data1=data.split(' ')
               print(data1)
               for i in range (len(data1)
                 dT=data1[i+1]-data[i]
               print dT
          

  df=pd.DataFrame(table).T
  
  df.plot()
 
    
  plt.xticks(
      ticks=range(len(df)),
      labels=df.index,
      rotation=45
    )
  plt.locator_params(axis='x',nbins=10)
  plt.xlabel('Time')
  plt.ylabel('Temperature')
  plt.title('Temperature vs Time ')
  plt.show()

main()
   

Have you tried something like this, to get the numbers into a list object?

number_list = []

with open('numbers', mode='r', encoding='UTF-8') as numbers:
    for n in numbers:
        number = n.strip()
        number_list.append(float(number))

This is going to be a problem. After the first execution, your file handle is gone. :man_facepalming: no, I’m wrong, somehow this works.

From reading your code it’s clear that the problem has a lot more parts than what you described earlier. It’s difficult to help without understanding what’s actually going on.

It works because the for loop grabs the thing to iterate over and holds onto it, so it doesn’t have to reevaluate each iteration. However, this IS still a very confusing line of code, and I would strongly recommend renaming the file to, say, file :slight_smile:

3 Likes

Okay. Thank you.

If you’re targeting at least Python 3.10, there’s itertools.pairwise which would help you easily iterate over your list of floats in the way you want.

Assuming the core difficulty here is “how do I check each overlapping, adjacent pair of the values, each time through the loop?”: in recent versions this is directly provided as itertools.pairwise like Kevin said. For more details and other approaches, please see:

It looks like part of that line got left out.