gpt4 book ai didi

Scala:将表格绘制到控制台

转载 作者:行者123 更新时间:2023-12-01 17:26:24 26 4
gpt4 key购买 nike

我需要在控制台中显示一个表格。

我的简单解决方案(如果您称其为“解决方案”)如下:

  override def toString() = {
var res = "\n"
var counter = 1;
res += stateDb._1 + "\n"
res += " +----------------------------+\n"
res += " + State Table +\n"
res += " +----------------------------+\n"
for (entry <- stateDb._2) {
res += " | " + counter + "\t | " + entry._1 + " | " + entry._2 + " |\n"
counter += 1;
}
res += " +----------------------------+\n"
res += "\n"
res

}

我们不必争论这一点

  • a 显示时看起来很糟糕
  • b 代码看起来有点困惑

实际上,这样的问题是针对 C# 提出的,但我也想知道 Scala 的一个很好的解决方案。

那么在 Scala 中将这样的表格绘制到控制台的(好/好/简单/其他)方法是什么?

-------------------------------------------------------------------------
| Column 1 | Column 2 | Column 3 | Column 4 |
-------------------------------------------------------------------------
| | | | |
| | | | |
| | | | |
-------------------------------------------------------------------------

最佳答案

我从当前项目中提取了以下内容:

object Tabulator {
def format(table: Seq[Seq[Any]]) = table match {
case Seq() => ""
case _ =>
val sizes = for (row <- table) yield (for (cell <- row) yield if (cell == null) 0 else cell.toString.length)
val colSizes = for (col <- sizes.transpose) yield col.max
val rows = for (row <- table) yield formatRow(row, colSizes)
formatRows(rowSeparator(colSizes), rows)
}

def formatRows(rowSeparator: String, rows: Seq[String]): String = (
rowSeparator ::
rows.head ::
rowSeparator ::
rows.tail.toList :::
rowSeparator ::
List()).mkString("\n")

def formatRow(row: Seq[Any], colSizes: Seq[Int]) = {
val cells = (for ((item, size) <- row.zip(colSizes)) yield if (size == 0) "" else ("%" + size + "s").format(item))
cells.mkString("|", "|", "|")
}

def rowSeparator(colSizes: Seq[Int]) = colSizes map { "-" * _ } mkString("+", "+", "+")
}

scala> Tabulator.format(List(List("head1", "head2", "head3"), List("one", "two", "three"), List("four", "five", "six")))
res1: java.lang.String =
+-----+-----+-----+
|head1|head2|head3|
+-----+-----+-----+
| one| two|three|
| four| five| six|
+-----+-----+-----+

关于Scala:将表格绘制到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7539831/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com