将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中数据对应不齐。请问大佬怎么修改一下

阅读 3.2k
1 个回答
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]]
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题