Python: Reading from a list of files where we read and return a list of tuples from the data in the form [(x,y), (x1,y1)]

Question:

I’m creating a function that takes in a list of files (all strings) with each having the format:

File 1:

x,y

x1,y1

File2:

x2,y2

x3,y3

I need to return both files in a single list of tuples.
I currently have the function reading thru the file and split/stripping it as so:

newLst
lst = [(tuple(x.strip().split()) for x in y]
newLst.append(lst)

A couple issues I’m having:

  • I’m getting a list per file (in this case 2 lists within a list) when I need them to be one big list of all the tuples [[(‘x,y’,), (‘x1, y1’,)],[(‘x2, y2’,), …)]]
  • My tuples instead of (‘x’,’y’) it’s returning as (‘x,y’,) with an extra comma

Expected Output:

[('x','y'), ...('x2','y2')]
Asked By: Mk2016

||

Answers:

  1. Use extend() to extend a list by appending elements from another iterator.

  2. You should split the string by ',', and then make results as a tuple.

def extend_from_file(file, lst):
    with open(file, 'r') as f:
        lst.extend([tuple(x.strip().split(',')) for x in f if x.strip()]) # and skip blank lines
Answered By: ILS
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.