【问题标题】:Fill lists in list with zeros if their length less than如果列表的长度小于,则用零填充列表中的列表
【发布时间】:2022-08-09 14:10:35
【问题描述】:

我有一个不同大小的列表列表,但我想让它们的长度都相同。例如,如果长度小于 5,则通过用零填充使它们的长度为 5,或者如果长度大于 5,则剪切列表。例如,我有一个列表:

foo = [
    [1, 2, 3],
    [1, 2, 3, 4, 5],
    [1, 2, 3, 4, 5, 6, 7]]
result = [
    [1, 2, 3, 0, 0],
    [1, 2, 3, 4, 5],
    [1, 2, 3, 4, 5]]

如果列表很大,您是否有最佳和快速解决方案的想法?

  • 你已经尝试过什么?即使是列表理解也应该很快,但如果你需要速度,你可以使用 NumPy 或 SciPy 之类的东西。您的性能要求是什么?

标签: python list


【解决方案1】:

列表理解

制作一个填充列表并使用切片来获得适当的长度。

n = 5
fill = [0] * n
result = [sublist[:n] + fill[len(sublist):] for sublist in foo]

【讨论】:

  • 附言我不能谈论性能,因为你没有提到你的要求。
【解决方案2】:
result = []
for sublist in foo:
    size = len(sublist)
    result.append(sublist[:5] + [0]*(5 - size))

【讨论】:

  • 它作为一个列表比较简单:result = [sublist[:5] + [0]*(5 - len(sublist)) for sublist in foo]。此外,它还避免了result.append() 的开销。
  • @wjandrea 我知道,我看到了你的答案。你认为赞成票来自哪里?
【解决方案3】:

实际上,我为我找到了一个非常快速的解决方案。如果您知道如何在没有 for 循环的情况下解决它,请发布。

for row in foo:
    while len(row) < 5:
        row.append(0)
    else:
        row[:5]

【讨论】:

  • 这不限制长行的长度
  • 现在它使长行更长?它只向短行添加 1 个元素。
  • 同意,没注意到。你说的对。
  • 现在它仍然不限制长行。 while else 不会像你想的那样做。
【解决方案4】:

为了执行此优化,我将 n = 5 之外的其他元素切片,并通过检查它们遗漏了多少元素,将未达到 n = 5 的元素替换为 0。

def listOptimization(foo, n):
    # slicing foo to have n elements on all child elements of foo
    for i in range(len(foo)):
        foo[i] = foo[i][:n]

    # optimizing
    for i in range(len(foo)):
        # check if foo child element is less than n
        # if true, append to the list with 0 depending on how many
        # elements to reach n
        if len(foo[i])<n:
            temp = n-len(foo[i])
            for x in range(temp):
                foo[i].append(0)

    return foo

【讨论】:

    【解决方案5】:
    result = [[bar[i] if i<len(bar)else 0 for i in range(5)] for bar in foo]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-14
      • 2020-09-15
      • 1970-01-01
      • 1970-01-01
      • 2015-03-02
      • 2017-06-17
      • 2019-03-12
      • 2023-02-26
      相关资源
      最近更新 更多