2017-04-14 27 views
1

我正在寫一個必須運行C++程序(已編譯)以便管理非常繁重的操作的python程序。Python - 將類似列表的字符串轉換爲列表列表的最快,最有效的方式

我把這個可執行文件的方式是subprocess.check_output()

這樣做,它返回一個很長的字符串類似如下:

executable_output_1 = [0.011, 0.544, 2.314], [7.895, 6.477, 2.573]

executable_output_2 = [4.255, 6.235, 7.566], [9.522, 7.321, 1.234]

type(executable_output) >>> <type 'str'>

在這個例子中,我寫了一個很短的字符串,但在r eal輸出非常長。

我想用python中的數據做一些操作,所以我需要列表列表(因爲我會多次調用該可執行文件)。

如何將該字符串轉換爲列表清單?

所需的輸出:

executables_outputs_list = [[[0.011, 0.544, 2.314], [7.895, 6.477, 2.573]], [[4.255, 6.235, 7.566], [9.522, 7.321, 1.234]]]

type(executable_output_list) >>> <type 'list'>

type(executable_output_list[0]) >>> <type 'list'>

type(executable_output_list[0][0][0]) >>> <type 'float'>

+0

我想用subprocess.check_output()調用看代碼。 – Back2Basics

+0

@ Back2Basics這很簡單:'check_output(['/ home/user/executable','/ home/user/image。png'])' – PyCV

+0

好吧,你可能會在'='上分割並在'['和']'中包裝字符串,然後使用'ast.literal_eval'。醜陋的,肯定的。 –

回答

3

使用ast.literal_eval

>>> from ast import literal_eval 
>>> executable_output = '[0.011, 0.544, 2.314], [7.895, 6.477, 2.573]' 
>>> literal_eval(executable_output) 
([0.011, 0.544, 2.314], [7.895, 6.477, 2.573]) 

這是一個tuple。要轉換爲list

>>> list(literal_eval(executable_output)) 
[[0.011, 0.544, 2.314], [7.895, 6.477, 2.573]] 
1

您可以使用Python的json包這應該是比ast.literal_eval更快。

# setup 
from ast import literal_eval 
import json 

executable_output_1 = "[0.011, 0.544, 2.314], [7.895, 6.477, 2.573]" 
executable_output_2 = "[4.255, 6.235, 7.566], [9.522, 7.321, 1.234]" 

outputs = (executable_output_1, executable_output_2) 

json方法具有以下時機:100000 loops, best of 3: 14.5 µs per loop

def extract(output_strings): 
    template = '{{"values": [{}]}}' 
    parse_func = lambda x: json.loads(template.format(x)) 
    return [parse_func(x)["values"] for x in output_strings] 

extract(outputs) 

>>> [[[0.011, 0.544, 2.314], [7.895, 6.477, 2.573]], 
    [[4.255, 6.235, 7.566], [9.522, 7.321, 1.234]]] 

ast方法與10000 loops, best of 3: 51.6 µs per loop 3×較慢爲虛設數據:

def extract_ast(output_strings): 
    return [list(literal_eval(x)) for x in output_strings] 

extract_ast(outputs) 

>>> [[[0.011, 0.544, 2.314], [7.895, 6.477, 2.573]], 
    [[4.255, 6.235, 7.566], [9.522, 7.321, 1.234]]] 

json方法隨着提高要分析的數據量。用下面的設置中,json方法的產率1000 loops, best of 3: 291 µs per loop相比ast100 loops, best of 3: 3.95 ms per loop這是13X更快。

executable_output_1 = ",".join(["[0.011, 0.544, 2.314], [7.895, 6.477, 2.573]"] * 100) 
executable_output_2 = ",".join(["[4.255, 6.235, 7.566], [9.522, 7.321, 1.234]"] * 100) 

outputs = (executable_output_1, executable_output_2) 
相關問題