Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def read_xy(file):
- """
- Read x and y values from file for each line
- and return a generator.
- The values are yielded like:
- [(x1,y1), (x2, y2), (x3, y3), ...]
- """
- with open(file) as fd:
- # fd is also a line iterator
- for line in fd:
- if not line.strip():
- # skip if line is empty
- continue
- values = line.split()
- if len(values) != 2:
- # skip if 0, 1 or 3+ values in one line
- continue
- try:
- x, y = map(int, values)
- except ValueError:
- # what to do if x or y is not an int?
- # actually skipping
- continue
- # this line could only be reached,
- # if all previous conditions are ok
- yield x, y
- if __name__ == "__main__":
- values = read_xy("test.txt")
- # values is a generator
- # values are lazy evaluated (saving memory)
- # trick to transpose an iterable
- x, y = zip(*values)
- print(f"X: {x}\nY: {y}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement