繁体   English   中英

从数据文件创建列表

[英]Creating lists from data file

我有一个预定义的列表,该列表以(最小,最大,增量)形式提供数据。 例如:

[[0.0 1.0 0.1 #mass 
  1.0 5.0 1.0 #velocity
  45.0 47.0 1.0 #angle in degrees
  0.05 0.07 0.1 #drag coeff.
  0.0 0.0 0.0 #x-position
  0.0 0.0 0.0]] #y-postion

并继续进行其他一些变量。 理想情况下,我想将每个变量都当作一个单独的变量声明,并为给定范围内的每个值创建一个有限列表。

例如,质量为:

m = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]

这样,我可以利用itertools.combinations((m, x, b,...), r)在给定每个变量各种可能性的情况下创建所有可能的组合。

有什么建议么?

您将列表写为平面列表,所有数字都在同一级别

[[0.0 1.0 0.1 1.0 5.0 1.0 45.0 47.0 1.0 ...]]

但您可能打算将其写为嵌套列表

[[0.0, 1.0, 0.1], [1.0, 5.0, 1.0], [45.0, 47.0, 1.0], ...]

所以我将展示两种解决方案。 请让我知道您的数据/列表的实际结构。

Python的range函数不支持浮点数,但是您可以使用NumPy的arange

try ... except部分用于保持不变的值,例如0.0 0.0 0.0 #x-position

平面清单解决方案:

flat_list = [0.0, 1.0, 0.1,
             1.0, 5.0, 1.0,
             45.0, 47.0, 1.0,
             0.05, 0.07, 0.1,
             0.0, 0.0, 0.0,
             0.0, 0.0, 0.0]
import numpy as np
incremented_lists = []
for i in range(0, len(flat_list), 3):  # Step in threes
    minimum, maximum, increment = flat_list[i:i+3]
    try:
        incremented_list = list(np.arange(minimum, maximum + increment, increment))
    except ZeroDivisionError:
        incremented_list = [minimum]
    incremented_lists.append(incremented_list)

嵌套列表解决方案:

nested_list = [[0.0, 1.0, 0.1],
               [1.0, 5.0, 1.0],
               [45.0, 47.0, 1.0],
               [0.05, 0.07, 0.1],
               [0.0, 0.0, 0.0],
               [0.0, 0.0, 0.0]]
import numpy as np
incremented_lists = []
for sub_list in nested_list:
    minimum, maximum, increment = sub_list
    try:
        incremented_list = list(np.arange(minimum, maximum + increment, increment))
    except ZeroDivisionError:
        incremented_list = [minimum]
    incremented_lists.append(incremented_list)

使用Python 2.7或Python 3.3运行以下任一命令均可:

incremented_lists: [[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0],
                    [1.0, 2.0, 3.0, 4.0, 5.0],
                    [45.0, 46.0, 47.0],
                    [0.05, 0.15],
                    [0.0],
                    [0.0]]

[0.05, 0.15]可能是不希望的,但是我认为阻力系数的0.1巨大增量比我应该使代码处理的东西更容易出现错字。 请让我知道您是否希望代码处理不自然的增量并避免超出最大值。 处理该问题的一种方法是,在incremented_lists.append(incremented_list)之前,立即添加incremented_list = [x for x in incremented_list if x <= maximum]

不确定列表结构,如果确实需要切片,则可以使用itertools.islice并将所有列表存储在dict中:

from itertools import islice

l = iter([0.0, 1.0, 0.1, #mass
  1.0, 5.0, 1.0,#velocity
  45.0 ,47.0, 1.0, #angle in degrees
  0.05, 0.07, 0.1, #drag coeff.
  0.0, 0.0 ,0.0 ,#x-position
  0.0 ,0.0, 0.0])#y-postion

d = {}

import numpy as np

for v in ("m","v","and","drg","x-p","y-p"): # put all "variable" names in order
    start, stop , step = islice(l, None, 3)
    # or use next()
    # start, stop , step = next(l), next(l), next(l)
    if stop > start: # make sure we have a step to take
        # create key/value pairing 
        d[v] = np.arange(start, stop + 1,step)
    else: 
         # add empty list for zero values
         d[v] = []

 print(d)
 {'x-p': [], 'drg': array([ 0.05,  0.15,  0.25,  0.35,  0.45,  0.55,  0.65,  0.75,  0.85,
    0.95,  1.05]), 'and': array([ 45.,  46.,  47.]), 'v': array([ 1.,  2.,  3.,  4.,  5.]), 'y-p': [], 'm': array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9,  1. ,
    1.1,  1.2,  1.3,  1.4,  1.5,  1.6,  1.7,  1.8,  1.9])}

您还可以创建自己的范围,以浮动为单位:

def float_range(start=0, stop=None, step=1):
    while start <= stop:
        yield start
        start += step

然后用list(start, stop,step)调用它,但是在处理浮点数时需要小心,因为浮点算术:问题和局限性

我想不出任何支持您想要的输入的现有格式-用空格作为分隔符,换行符打破子列表,并且在您似乎希望定义子列表名称时,注释实际上是有意义的。 因此,我认为您必须编写自己的解析器,例如:

import re, numpy as np

res_dict = {}
with open('thefile.txt') as f:
    for line in f:
        mo = re.match(r'[?[(\S+)\s*(\S+)\s*(\S+)\s*#(\w)', line)
        keybase = mo.group(4)
        keyadd = 0
        key = keybase
        while key in res_dict:
            key = '{}{}'.format(keybase, keyadd)
            keyadd += 1
        res_dict[key] = np.arange(
            float(mo.group(1)),
            float(mo.group(2)),
            float(mo.group(3)),
        )

正如您所提到的,这不会给您一个顶级变量m ,而是一个结构更好,更可靠的res_dict['m'] 如果您坚持要使代码脆弱易碎,则可以使 globals().update(res_dict)变为:-)...

暂无
暂无

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

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