登录
首页 >  Golang >  Go问答

表格数据如何改变列数?

来源:stackoverflow

时间:2024-02-05 22:27:25 482浏览 收藏

对于一个Golang开发者来说,牢固扎实的基础是十分重要的,golang学习网就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《表格数据如何改变列数?》,主要介绍了,希望对大家的知识积累有所帮助,快点收藏起来吧,否则需要时就找不到了!

问题内容

这是打印表格中数据的代码,每列包含多个数据。这样,每一列就很难打印出准确的数据数量。

这就是为什么如果数据数量为 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)
}

正确答案


有一系列可能的方法;这是一种无需对行/列数进行假设的选项 (playground):

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()
}

理论要掌握,实操不能落!以上关于《表格数据如何改变列数?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>