Advertisement
DeaD_EyE

readxy

Jan 11th, 2021
870
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.09 KB | None | 0 0
  1. def read_xy(file):
  2.     """
  3.    Read x and y values from file for each line
  4.    and return a generator.
  5.  
  6.    The values are yielded like:
  7.    [(x1,y1), (x2, y2), (x3, y3), ...]
  8.    """
  9.     with open(file) as fd:
  10.         # fd is also a line iterator
  11.         for line in fd:
  12.             if not line.strip():
  13.                 # skip if line is empty
  14.                 continue
  15.  
  16.             values = line.split()
  17.  
  18.             if len(values) != 2:
  19.                 # skip if 0, 1 or 3+ values in one line
  20.                 continue
  21.  
  22.             try:
  23.                 x, y = map(int, values)
  24.             except ValueError:
  25.                 # what to do if x or y is not an int?
  26.                 # actually skipping
  27.                 continue
  28.  
  29.             # this line could only be reached,
  30.             # if all previous conditions are ok
  31.             yield x, y
  32.  
  33.  
  34. if __name__ == "__main__":
  35.     values = read_xy("test.txt")
  36.     # values is a generator
  37.     # values are lazy evaluated (saving memory)
  38.  
  39.     # trick to transpose an iterable
  40.     x, y = zip(*values)
  41.  
  42.     print(f"X: {x}\nY: {y}")
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement