Search code examples
pythonjoinmultidimensional-arrayio

How to convert a 2D Array of records to a multi lined string of records separated by a delimiter?


I have a 2D array of records.

records = [['Adam', 'Smith', '11111985'], ['Theodore', 'Anderson', '20031990'], ['Adam K', 'Smith', '09091999'], ['Monty', 'Biscuit-Barrel', '18101980'], ['Adam', 'Smithers', '00000000'], ['Ruthy', 'Anderson', '06062010']]

I want to output these records to a file line by line, each line being a row of information, and each row having records separated with '|' delimiter. So the output is supposed to look like this:

Adam|Smith|11111985
Theodore|Anderson|20031990
Adam K|Smith|09091999
Monty|Biscuit-Barrel|18101980
Adam|Smithers|00000000
Ruthy|Anderson|06062010

However, this is what I'm getting for my output:

Adam|Smith|11111985|
|Theodore|Anderson|20031990|
|Adam K|Smith|09091999|
|Monty|Biscuit-Barrel|18101980|
|Adam|Smithers|00000000|
|Ruthy|Anderson|06062010|

And here is my code:

def makeTextFrom2dArray(records):
  tempArray = []

  for row in records:
    for col in row:
      tempArray.append(col)
    tempArray.append('\n')
  return ('|').join(tempArray)

output= makeTextFrom2dArray(records)
print(output)

Solution

  • You can do it with a generator expression which will reduce the amount of memory required.

    records = [['Adam', 'Smith', '11111985'], ['Theodore', 'Anderson', '20031990'],
               ['Adam K', 'Smith', '09091999'], ['Monty', 'Biscuit-Barrel', '18101980'],
               ['Adam', 'Smithers', '00000000'], ['Ruthy', 'Anderson', '06062010']]
    
    def makeTextFrom2dArray(records):
        tempArray = ('|'.join(group) for group in records)  # Generator expression.
        return '\n'.join(tempArray)
    
    output = makeTextFrom2dArray(records)
    print(output)
    

    Output:

    Adam|Smith|11111985
    Theodore|Anderson|20031990
    Adam K|Smith|09091999
    Monty|Biscuit-Barrel|18101980
    Adam|Smithers|00000000
    Ruthy|Anderson|06062010