将list转换为array失败?

将list转换为array失败?

我props变量里面是多个并排的list列表,每个列表里面有很多的int,dict.当我执行
props = np.array(props).报错setting an array element with a sequence. The requested array has an inhomogeneous shape after 2 dimensions. The detected shape was (20, 15) + inhomogeneous part.首先排除list中数据类型不一致的问题。我觉得应该是list中数据对应不齐。请问大佬怎么修改一下


回答:

import numpy as np

# Let's create a list of lists with uneven lengths and mixed types:

props = [[1, 2, 3, {'a': 1, 'b': 2}], [4, 5, 6, 7, {'c': 3, 'd': 4}], [8, 9, 10]]

# Check the lengths of the inner lists

lengths = [len(inner_list) for inner_list in props]

# Pad the shorter lists with None to make them all the same length

max_length = max(lengths)

padded_props = [inner_list + [None]*(max_length - len(inner_list)) for inner_list in props]

# Try converting the padded list of lists to a NumPy array

try:

np_props = np.array(padded_props)

print(np_props)

except Exception as e:

print(f"An error occurred: {e}")

输出:

[[1 2 3 {'a': 1, 'b': 2} None]

[4 5 6 7 {'c': 3, 'd': 4}]

[8 9 10 None None]]

以上是 将list转换为array失败? 的全部内容, 来源链接: utcz.com/p/938963.html

回到顶部