【发布时间】:2016-01-30 23:26:21
【问题描述】:
我一直在生成可变长度列表,一个简化的例子。
list_1 = [5] * 5
list_2 = [8] * 10
然后我想转换为 np.array 进行操作。因此,它们需要具有相同的长度(例如 1200),尾部要么填充零,要么在目标长度处截断。
对于 8 的固定长度,我考虑设置一个零数组,然后填充适当的条目:
np_list_1 = np.zeros(8)
np_list_1[0:5] = list_1[0:5]
np_list_2 = np.zeros(8)
np_list_2[0:8] = list_2[0:8] # longer lists are truncated
我创建了以下函数来生成这些
def get_np_fixed_length(list_like, length):
list_length = len(list_like)
np_array = np.zeros(length)
if list_length <= length:
np_array[0:list_length] = list_like[:]
else:
np_array[:] = list_like[0:length]
return np_array
有没有更有效的方法来做到这一点? (我在 numpy 文档中看不到任何内容)
【问题讨论】:
标签: python python-3.x numpy