【问题标题】:Pad list in PythonPython中的填充列表
【发布时间】:2011-12-04 14:01:12
【问题描述】:

在 python 中打印时如何填充列表?

例如,我有以下列表:

mylist = ['foo', 'bar']

我想打印这个填充到四个索引,用逗号。我知道我可以执行以下操作以将其作为逗号和空格分隔的列表:

', '.join(mylist)

但是我怎样才能用'x'将它填充到四个索引,所以输出是这样的:

foo, bar, x, x

【问题讨论】:

  • 以防万一:你不应该使用'list'作为变量名
  • 如果mylist 包含五个项目,你想要什么结果?
  • @EthanFurman,好问题,谢天谢地,我使用的代码永远不会发生这种情况。我想它应该显示为foo, bar, baz, qux, wibble

标签: python list padding


【解决方案1】:
In [1]: l = ['foo', 'bar']

In [2]: ', '.join(l + ['x'] * (4 - len(l)))
Out[2]: 'foo, bar, x, x'

['x'] * (4 - len(l)) 生成一个列表,其中包含填充所需的正确数量的 'x'entries。

编辑有一个问题是如果len(l) > 4 会发生什么。在这种情况下['x'] * (4 - len(l))results in an empty list,正如预期的那样。

【讨论】:

  • 如果 len(l) 大于 4 会怎样?
  • @ovgolovin:它按预期工作:将一个序列乘以一个负数会产生一个空序列(如果你想知道,这是记录在案的行为——我稍后会添加一个链接)。
【解决方案2】:

使用 itertools 的另一种可能性:

import itertools as it

l = ['foo', 'bar']

', '.join(it.islice(it.chain(l, it.repeat('x')), 4))

【讨论】:

    【解决方案3】:

    基于来自itertoolsgrouper() 配方:

    >>> L = ['foo', 'bar']
    >>> ', '.join(next(izip_longest(*[iter(L)]*4, fillvalue='x')))
    'foo, bar, x, x'
    

    它可能属于“不要在家尝试”类别。

    【讨论】:

      猜你喜欢
      • 2010-10-16
      • 1970-01-01
      • 1970-01-01
      • 2021-03-11
      • 2015-08-09
      • 2018-06-18
      • 1970-01-01
      • 2020-08-05
      • 2022-01-08
      相关资源
      最近更新 更多