简体   繁体   English

如何将长长的python列表格式化为Fortran多行数组?

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

I have a problem. 我有个问题。 I am programming a math calculation program in Fortran. 我正在用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. 这些值必须正态分布,平均值为0,标准差为1。

I did the following script in Python 2.7 to generate 900 of such values. 我在Python 2.7中执行了以下脚本,以生成900个这样的值。

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: 问题是我不能仅仅将其复制到我的Fortran代码中,因为其中的值是通过以下方式编写的:

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: 这意味着我必须将Python列表的格式设置为:

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

How would I go about doing this? 我将如何去做呢?

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: 使用此答案中的配方将您的列表分为N个值组,然后只需遍历各组即可:

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. 请注意,您必须重命名list变量,以避免与内置列表类型冲突。

Instead of using itertools, I've just split the list with a for loop and then printer each element with another. 我没有使用itertools,而是使用for循环拆分了列表,然后用另一个元素打印了每个元素。

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]) + ', &'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM