从数据文件创建列表

时间:2015-02-23 01:04:51

标签: python list combinatorics

我有一个预定义的列表,以(min,max,increment)的形式提供数据。例如:

[[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)创建所有可能的组合,给出每个变量的各种可能性。

有什么建议吗?

3 个答案:

答案 0 :(得分:1)

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

[[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_list = [x for x in incremented_list if x <= maximum]之前添加incremented_lists.append(incremented_list),但我确信有一种更简洁的方法。

答案 1 :(得分:1)

不确定列表结构,如果你需要采取切片,你可以使用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)调用它,但由于Floating Point Arithmetic: Issues and Limitations

,在处理浮点数时需要小心

答案 2 :(得分:0)

我无法想到任何支持所需输入的现有格式 - 空格作为分隔符,新行打破子列表,并且注释实际上有意义,因为您似乎希望定义子列表的名称。所以,我认为你必须编写自己的解析器代码,例如:

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)这样做: - )......