【问题标题】:Function to print out a external representation打印外部表示的功能
【发布时间】:2015-12-05 19:43:08
【问题描述】:

我的问题是创建一个函数,接收一个元组,打印出如下所示的表示,其中的空格(对应于其他行中的数字)用空字符串填充。行数由具有最多条目的元组给出,例如,如果所有元组只有 1 个条目,则只有一行,如果其中一个元组有 2 个条目,则将有 2 行。 谁能告诉我这样做的有效方法? the image of the representation I want is in this picture.

例如,如果某个元组中有 3 个条目,则会有 3 行,依此类推。

图片是这样的:

   1
2  2  2  3  3

【问题讨论】:

  • 给我们一些代码。到目前为止你尝试过什么?

标签: python function output


【解决方案1】:
from itertools import zip_longest

# test data
test = [(2,), (2, 1), (2,), (3,), (3,)]

# rearrange data into same-length columns
lines = list(zip_longest(*test, fillvalue=" "))

# show results
lines.reverse()
for line in lines:
    print("   ".join(str(i) for i in line))

生产

    1
2   2   2   3   3

【讨论】:

  • 感谢您的快速响应,但有没有使用迭代的方法?以 for cicle 为例?
  • docs.python.org/3/library/itertools.html#itertools.zip_longest 有一个 zip_longest 的配方除此之外:我建议遍历数据以找到最长的项目,一次遍历将所有内容填充到该长度,然后 for row in range(longest-1, -1, -1): print(" ".join(col[row] for col in data))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-10
  • 2020-11-22
  • 2017-01-25
  • 2019-12-22
  • 1970-01-01
  • 2014-11-29
  • 2022-01-01
相关资源
最近更新 更多