python - 从数据文件创建列表

标签 python list combinatorics

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

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

有什么建议吗?

最佳答案

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

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])}

您还可以创建自己的范围,以 float 为步长:

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

然后用list(start, stop,step)调用它,但是在处理 float 时需要小心,因为Floating Point Arithmetic: Issues and Limitations

关于python - 从数据文件创建列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28665506/

相关文章:

python - 根据同一数据框的另一列更新分数列

python - 两个 for 循环,第二个仅在第一次迭代时执行 python

python - Kml 创建错误

python - 字母表和递归

c++ - C++ 中的分区和组合(组合)实现

python - Python 中的二叉树计数范围内的节点

python - 为什么修改数组的副本会影响原始数组?

Java 组合生成

algorithm - 计算用两种瓷砖尺寸 build 一堵墙的方法

python - 如何使用 ([start ,] stop [, step]) 之类的签名实现 python 方法,即左侧的默认关键字参数