How to format a long python list into a Fortran multi-line array?

115 views Asked by At

I have a problem. I am programming a math calculation program in Fortran. In there I have to initialize an array of random values. These values have to be normally distributed with a mean of 0 and a standard deviation of 1.

I did the following script in Python 2.7 to generate 900 of such values.

import numpy as np

mu, sigma = 0, 1.0
list = []

i = 0
while i < 901:
    s = np.random.normal(mu, sigma, None)
    list.append(format(s, '.3f'))
    i += 1

print list

This returns this list:

['-1.403', '-1.498', '0.573', '-0.056', '-0.226', '-0.514', ..., ]

The problem is that I can't just copy this into my Fortran code because the values there are written in the following way:

DATA STR / 0.978,  -0.52 ,  -0.368,   1.69 ,  &   !Giving random values. Temperary solution for
          -1.48 ,   0.985,   1.475,  -0.098,  &   !random number generating, based on the normal law
          -1.633,   2.399,   0.261,  -1.883,  &
          -0.181,   1.675,  -0.324,  -1.029,  &
          -0.185,   0.004,  -0.101,  -1.187,  &
          -0.007,   1.27 ,   0.568,  -1.27 ,  &
           ... &
           ... &
           ... &

           /

Meaning that I have to format the Python list into something like:

NUM1, NUM2, NUM3, NUM4, &
XXXX, XXXX, XXXX, XXXX, &
...
...
...

How would I go about doing this?

2

There are 2 answers

0
David Simon Tetruashvili On

Instead of using itertools, I've just split the list with a for loop and then printer each element with another.

import numpy as np


mu, sigma = 0, 1.0
alist = []

i = 0
while i < 900:
    s = np.random.normal(mu, sigma, None)
    alist.append(format(s, '.3f'))
    i += 1


new = []

for i in range(0, len(alist), 4):
    new.append(alist[i : i + 4])

for i in range(len(new)):
    print ', '.join(new[i]) + ', &'
1
iCart On

Use the recipe in this answer to split your list in groups of N values, then it's just a matter of iterating through the groups:

for group in grouper(4, lst):
    for value in group:
        print(list(group).join(', '))
    print('&')

Note that you'll have to rename the list variable to avoid clashing with the builtin list type.