我必須將一堆整數格式的 UUID 存盤在一個 numpy 陣列中。將 UUID 轉換為整數格式(128 位)無效,因為可以存盤在 numpy 陣列中的最大整數大小為 64 位。因此,我嘗試使用欄位樣式將 UUID 存盤為 6 個單獨的整數。
但是我無法從 numpy 陣列值重新創建 UUID。這是問題的一個例子。
import uuid
#generate a random uuid4
my_uuid = uuid.uuid4()
my_uuid
# UUID('bf6cc180-52e1-42fe-b3fb-b47d238ed7ce')
# encode the uuid to 6 integers with fields
my_uuid_fields = my_uuid.fields
my_uuid_fields
# (3211575680, 21217, 17150, 179, 251, 198449560475598)
# recreate the uuid, this works
uuid.UUID(fields=my_uuid_fields)
# UUID('bf6cc180-52e1-42fe-b3fb-b47d238ed7ce')
# create an array with the fields
my_uuid_fields_arr = np.array(my_uuid_fields)
my_uuid_fields_arr
# array([3211575680,21217,17150,179,251,198449560475598])
# convert array back to tuple and check if its the same as the initial fields tuple
assert tuple(my_uuid_fields_arr) == my_uuid_fields
# this fails however
uuid.UUID(fields = tuple(my_uuid_fields_arr))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
/scratch/6084717/ipykernel_43199/1198120499.py in <module>
----> 1 uuid.UUID(fields = tuple(my_uuid_fields_arr))
/hpc/compgen/users/mpages/software/miniconda3/envs/babe/lib/python3.7/uuid.py in __init__(self, hex, bytes, bytes_le, fields, int, version, is_safe)
192 if int is not None:
193 if not 0 <= int < 1<<128:
--> 194 raise ValueError('int is out of range (need a 128-bit value)')
195 if version is not None:
196 if not 1 <= version <= 5:
ValueError: int is out of range (need a 128-bit value)
關于如何解決這個問題的任何想法?
uj5u.com熱心網友回復:
tuple(my_uuid_fields_arr)是 的元組np.int64,而my_uuid_fields是 的元組int。顯然uuid無法正確處理 numpy 整數。
只需將 numpy 整數轉換為 python 整數。
uuid.UUID(fields = tuple([int(i) for i in my_uuid_fields_arr]))
當您檢查type任一元組中的第一項時,您可以驗證這是問題所在。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/409731.html
標籤:
上一篇:顫振飛鏢顯示錯誤
