根据表中的数据如何增加或减少列数?

huangapple go评论102阅读模式
英文:

How to increase or decrease the number of columns according to data in table?

问题

这是一个打印数据表格的代码,每一列包含多个数据。因此,每一列打印的数据数量可能不一致。

如果数据数量为3,并且循环的限制为2,那么最后一列的数据将不会被打印出来,并且循环会在2处停止。

如何根据数据调整列数?

期望结果

╔═══╤════════════════╤═════════════════════╗
║ # │    项目        │ 项目优先级          ║
╟━━━┼━━━━━━━━━━━━━━━━┼━━━━━━━━━━━━━━━━━━━━━╢
║ 1 │ 第一个项目     │       无            ║
║ 2 │ 第二个项目     │       低            ║
║ 3 │                │      中等           ║
║ 4 │                │       高            ║
╚═══╧════════════════╧═════════════════════╝

代码

package main

import (
	"fmt"

	"github.com/alexeyco/simpletable"
)

func InfoTable(allData [][]string) {
	table := simpletable.New()
	table.Header = &simpletable.Header{
		Cells: []*simpletable.Cell{
			{Align: simpletable.AlignCenter, Text: "#"},
			{Align: simpletable.AlignCenter, Text: "项目"},
			{Align: simpletable.AlignCenter, Text: "项目优先级"},
		},
	}

	var cells [][]*simpletable.Cell

	for i := 0; i < 2; i++ {
		cells = append(cells, &[]*simpletable.Cell{
			{Align: simpletable.AlignCenter, Text: fmt.Sprintf("%d", i+1)},
			{Align: simpletable.AlignCenter, Text: allData[0][i]},
			{Align: simpletable.AlignCenter, Text: allData[1][i]},
		})
	}

	table.Body = &simpletable.Body{Cells: cells}

	table.SetStyle(simpletable.StyleUnicode)
	table.Println()
}

func main() {
	data := [][]string{
		{"第一个项目", "第二个项目"},
		{"无", "低", "中等", "高"},
	}
	InfoTable(data)
}
英文:

this is the code that prints the data in a table and each column contains multiple numbers of data. In this way, it is difficult for each column to print the exact number of data.

That's why if the number of data is three and the loop has the limit of 2 then it will not print the last data column and the loop will stop at 2.

How to adjust the columns according to data?

Required Result

╔═══╤════════════════╤═════════════════════╗
║ # │    Projects    │ Project Priorities  ║
╟━━━┼━━━━━━━━━━━━━━━━┼━━━━━━━━━━━━━━━━━━━━━╢
║ 1 │ first project  │       None          ║
║ 2 │ second project │       Low           ║
║ 3 │                │      Medium         ║
║ 4 │                │       High          ║
╚═══╧════════════════╧═════════════════════╝

Code

package main

import (
	&quot;fmt&quot;

	&quot;github.com/alexeyco/simpletable&quot;
)

func InfoTable(allData [][]string) {
	table := simpletable.New()
	table.Header = &amp;simpletable.Header{
		Cells: []*simpletable.Cell{
			{Align: simpletable.AlignCenter, Text: &quot;#&quot;},
			{Align: simpletable.AlignCenter, Text: &quot;Projects&quot;},
			{Align: simpletable.AlignCenter, Text: &quot;Project Priorities&quot;},
		},
	}

	var cells [][]*simpletable.Cell

	for i := 0; i &lt; 2; i++ {
		cells = append(cells, *&amp;[]*simpletable.Cell{
			{Align: simpletable.AlignCenter, Text: fmt.Sprintf(&quot;%d&quot;, i+1)},
			{Align: simpletable.AlignCenter, Text: allData[0][i]},
			{Align: simpletable.AlignCenter, Text: allData[1][i]},
		})
	}

	table.Body = &amp;simpletable.Body{Cells: cells}

	table.SetStyle(simpletable.StyleUnicode)
	table.Println()
}

func main() {
	data := [][]string{
		{&quot;first project&quot;, &quot;second project&quot;},
		{&quot;None&quot;, &quot;Low&quot;, &quot;Medium&quot;, &quot;High&quot;},
	}
	InfoTable(data)
}

答案1

得分: 1

有多种可能的方法;这里是一种选项,它消除了对行/列数量做出假设的需要(playground):

func InfoTable(headings []string, allData [][]string) {
	if len(headings) != len(allData) {
		panic("每列必须有一个标题")
	}
	table := simpletable.New()

	// 填充标题(为行号添加一个标题)
	headerCells := make([]*simpletable.Cell, len(headings)+1)
	headerCells[0] = &simpletable.Cell{Align: simpletable.AlignCenter, Text: "#"}
	for i := range headings {
		headerCells[i+1] = &simpletable.Cell{Align: simpletable.AlignCenter, Text: headings[i]}
	}

	table.Header = &simpletable.Header{
		Cells: headerCells,
	}

	// 计算所需的行数
	noOfCols := len(allData)
	noOfRows := 0
	for _, col := range allData {
		if len(col) > noOfRows {
			noOfRows = len(col)
		}
	}

	// 填充单元格(添加行号)
	cells := make([][]*simpletable.Cell, noOfRows)
	for rowNo := range cells {
		row := make([]*simpletable.Cell, noOfCols+1) // 添加行号列
		row[0] = &simpletable.Cell{Align: simpletable.AlignCenter, Text: fmt.Sprintf("%d", rowNo+1)}

		for col := 0; col < noOfCols; col++ {
			if len(allData[col]) > rowNo {
				row[col+1] = &simpletable.Cell{Align: simpletable.AlignCenter, Text: allData[col][rowNo]}
			} else {
				row[col+1] = &simpletable.Cell{Align: simpletable.AlignCenter, Text: ""} // 空单元格
			}
			cells[rowNo] = row
		}
	}
	table.Body = &simpletable.Body{Cells: cells}

	table.SetStyle(simpletable.StyleUnicode)
	table.Println()
}
英文:

There are a range of possible approaches; here is one option that removes the need to make assumptions about the number of rows/columns (playground):

func InfoTable(headings []string, allData [][]string) {
	if len(headings) != len(allData) {
		panic(&quot;Must have a heading per column&quot;)
	}
	table := simpletable.New()

	// Populate headings (adding one for the row number)
	headerCells := make([]*simpletable.Cell, len(headings)+1)
	headerCells[0] = &amp;simpletable.Cell{Align: simpletable.AlignCenter, Text: &quot;#&quot;}
	for i := range headings {
		headerCells[i+1] = &amp;simpletable.Cell{Align: simpletable.AlignCenter, Text: headings[i]}
	}

	table.Header = &amp;simpletable.Header{
		Cells: headerCells,
	}

	// Work out number of rows needed
	noOfCols := len(allData)
	noOfRows := 0
	for _, col := range allData {
		if len(col) &gt; noOfRows {
			noOfRows = len(col)
		}
	}

	// Populate cells (adding row number)
	cells := make([][]*simpletable.Cell, noOfRows)
	for rowNo := range cells {
		row := make([]*simpletable.Cell, noOfCols+1) // add column for row number
		row[0] = &amp;simpletable.Cell{Align: simpletable.AlignCenter, Text: fmt.Sprintf(&quot;%d&quot;, rowNo+1)}

		for col := 0; col &lt; noOfCols; col++ {
			if len(allData[col]) &gt; rowNo {
				row[col+1] = &amp;simpletable.Cell{Align: simpletable.AlignCenter, Text: allData[col][rowNo]}
			} else {
				row[col+1] = &amp;simpletable.Cell{Align: simpletable.AlignCenter, Text: &quot;&quot;} // Blank cell
			}
			cells[rowNo] = row
		}
	}
	table.Body = &amp;simpletable.Body{Cells: cells}

	table.SetStyle(simpletable.StyleUnicode)
	table.Println()
}

huangapple
  • 本文由 发表于 2022年9月21日 15:59:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/73797238.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定