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

  • 本文关键字:增加 数据 何根 loops go
  • 更新时间 :
  • 英文 :


这是在表中打印数据的代码,每列包含多个数据编号。这样,每列都很难打印出确切数量的数据。

这就是为什么如果数据的数量是3,并且循环的限制是2,那么它将不会打印最后一个数据列,并且循环将在2处停止。

如何根据数据调整列?

所需结果

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

代码

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: "Projects"},
{Align: simpletable.AlignCenter, Text: "Project Priorities"},
},
}
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{
{"first project", "second project"},
{"None", "Low", "Medium", "High"},
}
InfoTable(data)
}

有一系列可能的方法;这里有一个选项可以消除对行/列(操场(数量的假设:

func InfoTable(headings []string, allData [][]string) {
if len(headings) != len(allData) {
panic("Must have a heading per column")
}
table := simpletable.New()
// Populate headings (adding one for the row number)
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,
}
// Work out number of rows needed
noOfCols := len(allData)
noOfRows := 0
for _, col := range allData {
if len(col) > 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] = &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: ""} // Blank cell
}
cells[rowNo] = row
}
}
table.Body = &simpletable.Body{Cells: cells}
table.SetStyle(simpletable.StyleUnicode)
table.Println()
}

最新更新