2017-08-28 39 views
1

我有與佈置在3個對象的元組數objedos列表的陣列...變換對象的數組到對象id

l = [(ob1, ob2, ob3), (ob1, ob3, ob4), (ob4, ob5, ob6), ...] 

隨着numpy的我可以離開該列表平坦

a = np.array(l) 
a = a.ravel() 

我差點一組ID與a.tobytes()

但我仍然沒有成功:\

如何將對象數組轉換爲對象ID數組?

回答

0

什麼阻止您使用id函數?此外,你在說什麼東西?我在問,因爲元組實際上也是對象。 但是,假設你是在談論IDS的OBS,在這裏你去:

object_ids = map(id, np.asarray(l).flatten()) 

編輯:

哦,其實,如果你想對象ID數組,那麼也許你應該去喜歡這樣的:

get_ids = np.vectorize(lambda obj: id(obj)) 
array_of_obj_ids = get_ids(np.asarray(list_of_objects).flatten()) 
+0

井的變化檢查,我已經有效地通過'np.frombuffer得到ID的列表(a.tobytes(),D型細胞=「U8」) '但我真的很喜歡'vectorize'函數,所以我將其標記爲答案:) –

+0

@ Mano-Wii我很樂意提供幫助!是的,我的解決方案似乎更簡潔一些。這不是很明顯,'np.frombuffer(a.tobytes(),dtype ='u8')'做了什麼。 :) – Foobard

0

如果你不想複製數組的內容,你可以使用這個技巧與ctypes的:

import ctypes 
import numpy as np 

def switch_funcs(func1, func2):  
    from types import FunctionType 
    assert isinstance(func1, FunctionType) 
    assert isinstance(func2, FunctionType) 

    size = FunctionType.__basicsize__ 

    func1_ptr = (ctypes.c_char * size).from_address(id(func1)) 
    func2_ptr = (ctypes.c_char * size).from_address(id(func2)) 

    store = (ctypes.c_char * size)(*func1_ptr) 
    func1_ptr[:] = func2_ptr[:] 
    func2_ptr[:] = store[:] 


def dummy(*args, **vargs): 
    pass 

a = np.array([(ob1, ob2, ob3), (ob1, ob3, ob4), (ob4, ob5, ob6)]) 

switch_funcs(dummy, np.core._internal._view_is_safe) 
b = a.view(dtype = 'u8') 
switch_funcs(dummy, np.core._internal._view_is_safe) 

print(b) 

它暫時去除,以防止從D類對象UINT64