0

I'm new to Python, and don't know how to code this nicely (or even to search for the answer).

I'm reading data from a fixed-width file:

for line in file:
    dataline = [ line[c[0]:c[1]] for c in columns ]

which gives me an array of strings:

>>> dataline
['    ', ' 2.447756', '0.674290', '313.2406', ' 35.7290', ' 17.8714', 'PAHFTEN                            ']

For each line in the file, I would like to shift each element of dataline into a different array, e.g.,

dataline[0] ---> arrayA[0]
dataline[1] ---> arrayB[0]
dataline[2] ---> arrayC[0]

and so on. How can I do that nicely? Intuitively, I would like to do:

[arrayA[0], arrayB[0], arrayC[0], ...] = dataline
Unstack
  • 551
  • 3
  • 7
  • 13
  • @Unstack, seems like you need `zip()`: https://docs.python.org/2/library/functions.html#zip – mishik Feb 06 '15 at 12:15
  • did you consider using a `dict`? – wolfrevo Feb 06 '15 at 12:16
  • @mishik zip would be the final step. But I think he is asking for making the arrays that will be used in `zip`. – Barun Sharma Feb 06 '15 at 12:16
  • You can also consider making a list of lists(2D array). – Barun Sharma Feb 06 '15 at 12:19
  • looks like you need `reduce(lambda x, y: x + [y], zip(arrayA, arrayB, arrayC), [])` – robert Feb 06 '15 at 12:24
  • 1
    You could consider using a dictionary as follows: columns = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] dataline = [' ', ' 2.447756', '0.674290', '313.2406', ' 35.7290', ' 17.8714', 'PAHFTEN '] print dict(zip(columns, dataline)) – wolfrevo Feb 06 '15 at 12:25
  • @wolfrevo And then append to each dict value for each line of data... I see – Unstack Feb 06 '15 at 12:28
  • yes. declare an array(!) `datalines=[]` before the for-loop and append the result to it: `datalines.append(dict(zip(columns,dataline)))`. Then you can access e.g. line 4, column 'b' as follows `datalines[3]['b']` – wolfrevo Feb 06 '15 at 12:32
  • @robert Sounds like an elegant answer, but I have no idea what it means! – Unstack Feb 06 '15 at 13:55
  • It's definitely the way to go for the kind of problem you are describing: http://www.linuxtopia.org/online_books/programming_books/python_programming/python_ch20s03.html these kind of "functional programming" constructs loop implicitly. – robert Feb 06 '15 at 14:01

0 Answers0