【问题标题】:How to convert list of arrays of different length into arrays of same lenth in python [closed]如何在python中将不同长度的数组列表转换为相同长度的数组[关闭]
【发布时间】:2020-03-25 01:31:34
【问题描述】:

enter image description here

变成这样: [[1,0,0,0,0],[0.57735027, 0.57735027, 0.57735027,0,0],[0.57735027, 0.57735027, 0.57735027,0,0]等]

【问题讨论】:

  • 请不要将代码发布为图片。将您开始使用的实际列表添加为文本,并使用编辑器中的<> 按钮将其格式化为代码。
  • 这个问题的标题有点误导,也许你应该说:“如何在python中将不同长度的数组列表转换为相同长度的数组”

标签: python arrays


【解决方案1】:

也许,您正在寻找类似的东西:

data = [[1],[0.52, 0.53, 0.54],[],[0.1, 0.2, 0.3, 0.4, 0.5]]
max_size = 0

# identify the maximum length, for any of the lists in data
for arr in data:
    max_size = max(max_size, len(arr))

# extend each lists as required
for arr in data:
    # NOTE: the following should work, since the (max_size >= len(arr)) condition will always hold in this case
    arr.extend([0] * (max_size - len(arr)))

print(data)

注意:也会有更好的方法。但是,这可能会给你一个方向。

【讨论】:

    【解决方案2】:
    master_array = []
    
    for a in yourArray:
       master_array.extend(a)
    

    【讨论】:

    • 虽然这可能会回答问题,但它已被标记为待审核。没有解释的答案通常被认为是低质量的。请提供一些评论,说明为什么这是正确答案。
    【解决方案3】:

    你可以使用这个(假设它被称为列表):

    mxlen=max(len(i) for i in lists)
    for i in lists:
        i.extend([0]*(mxlen-len(i)))
    

    【讨论】:

      【解决方案4】:

      你可以尝试做这样的事情:

      yourArray =  [[1,0,0,0,0],[0.57735027, 0.57735027, 0.57735027,0,0],[0.57735027, 0.57735027, 0.57735027,0,0],and so on]
      
      outputArray = []
      
      for subArr in yourArray:
          [outputArray.append(i) for i in subArr]
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-18
        • 2019-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-26
        • 1970-01-01
        相关资源
        最近更新 更多