简体   繁体   English

Python:需要帮助将十六进制值字符串转换为 numpy 数组

[英]Python: Need help converting a string of hex values into numpy array

I am very much a Python beginner using Thonny and Python 3.7.7.我非常喜欢使用 Thonny 和 Python 3.7.7 的 Python 初学者。 I have strings of values that I want to convert to integers and put in a numpy array.我有要转换为整数并放入 numpy 数组的值字符串。 A typical string:一个典型的字符串:

print(temp)
05:01:00016043:00002F4F:00002F53:00004231:000050AA:00003ACE:00005C44:00003D3B:000064BC

temp = temp.split(":")
print(temp)

['05', '01', '00016043', '00002F4F', '00002F53', '00004231', '000050AA', '00003ACE', '00005C44', '00003D3B', '000064BC']

I want to efficiently turn this list of strings describing hexadecimal numbers into integers and put them into an numpy array (with the emphasis on efficiently.).我想有效地将这个描述十六进制数字的字符串列表转换为整数,并将它们放入 numpy 数组中(重点是高效。)。

a = np.array([11], dtype=int)

Any suggestions?有什么建议么? Thanks谢谢

How about a nice and tidy one-line list comprehension?一个漂亮整洁的单行列表理解怎么样? For a string s :对于字符串s

np.array([int(hexa, base=16) for hexa in s.split(sep=":")])

This may look complicated, but the output of s.split(sep=":") is a list of string hexadecimals.这可能看起来很复杂,但s.split(sep=":")的 output 是字符串十六进制列表。 Passing each one of them (each hexa ) into int with base=16 converts them, as you'd like.将它们中的每一个(每个hexa )传递给 int 并使用base=16转换它们,如您所愿。

Apply function which converts x to int(x, 16) to every element in L应用 function 将 x 转换为 int(x, 16) 到 L 中的每个元素

import pandas as pd
import numpy as np

L = ['05', '01', '00016043', '00002F4F', '00002F53', '00004231', '000050AA', '00003ACE', '00005C44', '00003D3B', '000064BC']
output = pd.Series(L).apply(lambda x:int(x, 16)).values
print(output)

output is output 是

[    5     1 90179 12111 12115 16945 20650 15054 23620 15675 25788]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM