簡體   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