0


浅谈Golang等多种语言转数组成字符串

Python

python语言中没有普通的数组,使用list类代替。转字符串非常方便,基本上所有的对象都有相应的内置方法__repr__()可以把obj转成对应的字串,对应的内置函数为 repr()。

help(repr)
Help on built-in function repr in module builtins:

repr(obj, /)
Return the canonical string representation of the object.

 For many object types, including most builtins, eval(repr(obj)) == obj.

示例:

>>> a = [1,2,3,4]
>>> b = [[1, 2],[3, 4],[5, 6]]
>>> c = [[1, 2], [3, 4], [5, [7,8,9]]]
>>> repr(a)
'[1, 2, 3, 4]'
>>> repr(b)
'[[1, 2], [3, 4], [5, 6]]'
>>> repr(c)
'[[1, 2], [3, 4], [5, [7, 8, 9]]]'

一维列表转字符串

.join()方法 + 列表推导式(看作是简版的循环遍历):

>>> a = [1, 2, 3, 4]
>>> "[" + ",".join(str(elem) for elem in a) + "]"
'[1,2,3,4]'

更 Pythonic 的写法:

>>> a = [1,2,3,4]
>>> ",".join(map(str,a)).join("[]")
'[1,2,3,4]'

二维列表转字符串

>>> b = [[1,2],[3,4]]
>>> ",".join(",".join(map(str,a)).join("[]") for a in b).join("[]")
'[[1,2],[3,4]]'

多维列表转字符串

可以自定义一个递归函数来模拟__repr__()的实现:

>>> from typing import List
>>> def List2Str(s):
    if not s:
        return '[]'
    pieces = []
    for item in s:
        if isinstance(item, List):
            pieces.append(List2Str(item))
        else:
            pieces.append(str(item))
    return ','.join(pieces).join('[]')

>>> a = [1, 2, 3, 4]
>>> b = [[1, 2], [3, 4]]
>>> c = [[1, 2], [3, 4], [5, [7, 8, 9]]]
>>> List2Str(a)
'[1,2,3,4]'
>>> List2Str(b)
'[[1,2],[3,4]]'
>>> List2Str(c)
'[[1,2],[3,4],[5,[7,8,9]]]'

对python来说,其实是不需要转换的,大可直接使用repr(), str(), print()来处理列表,也不用管列表元素是什么数据类型,非常省心。


Golang

go语言没有现成的list,vector容器类,只有数组和切片,可以被直接打印,但是用空格分隔的:

package main

import "fmt"

func main() {
    a := []int{1, 2, 3, 4}
    b := [][]int{{1, 2}, {3, 4}, {5, 6, 7}}
    fmt.Println(a)
    fmt.Println(b)
}

输出:

[1 2 3 4]
[[1 2] [3 4] [5 6 7]]

非要用逗号分隔,用strings.ReplaceAll()来替换,这种方法可以用在任意维数组上。

package main

import (
    "fmt"
    "strings"
)

func main() {
    a := []int{1, 2, 3, 4}
    b := [][]int{{1, 2}, {3, 4}, {5, 6, 7}}
    str := strings.ReplaceAll(fmt.Sprint(a), " ", ",")
    fmt.Println(str)
    str = strings.ReplaceAll(fmt.Sprint(b), " ", ",")
    fmt.Println(str)
}

输出:

[1,2,3,4]
[[1,2],[3,4],[5,6,7]]

对于一维数组,也有类似python中.join()方法:

package main

import (
    "fmt"
    "strings"
)

func main() {
    a := []int{1, 2, 3, 4}
    str := strings.Join(strings.Fields(fmt.Sprint(a)), ",")
    fmt.Println(str)
}

一维数组的遍历打印

​package main

import "fmt"

func ArrayToString(arr []int) string {
    res := "["
    for i := 0; i < len(arr); i++ {
        res += fmt.Sprint(arr[i]) //对[]int数组可以用strconv.Itoa(arr[i])
        if i != len(arr)-1 {
            res += ","
        }
    }
    return res + "]"
}

func main() {
    arr := []int{1, 2, 3, 4, 5}
    fmt.Println(ArrayToString(arr))
}

二维数组的遍历打印

package main

import "fmt"

func Array2DToString(array [][]int) string {
    if len(array) == 0 {
        return "[]"
    }
    arr2str := func(arr []int) string {
        res := "["
        for i, ar := range arr {
            res += fmt.Sprint(ar)
            if i != len(arr)-1 {
                res += ","
            }
        }
        return res + "]"
    }
    res := "["
    for i, arr := range array {
        res += arr2str(arr)
        if i != len(array)-1 {
            res += ","
        }
    }
    return res + "]"
}

func main() {
    arr := [][]int{{1, 2}, {3, 4}, {5, 6, 7}}
    fmt.Println(Array2DToString(arr))
}

或者:

package main

import (
    "fmt"
    "strings"
)

func Array2DToString(array [][]int) string {
    if len(array) == 0 {
        return "[]"
    }
    arr2str := func(arr []int) string {
        res := "["
        for i := 0; i < len(arr); i++ {
            res += fmt.Sprint(arr[i])
            if i != len(arr)-1 {
                res += ","
            }
        }
        return res + "]"
    }
    res := make([]string, len(array))
    for i, arr := range array {
        res[i] = arr2str(arr)
    }
    return strings.Join(strings.Fields(fmt.Sprint(res)), ",")
}

func main() {
    arr := [][]int{{1, 2}, {3, 4}, {5, 6, 7}}
    fmt.Println(Array2DToString(arr))
}

以上示例代码输出的都是紧凑形式[1,2,3,4],喜欢有空格如[1, 2, 3, 4],可以在以上代码中用", "代替","。


Java

一维容器的直接打印

java的数据类型超级丰富,甚至可以说是泛滥成灾了。容器类可以直接打印,普通数组不行:

import java.util.*;
public class main {
    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4};
        System.out.println(a);
        Integer[] b = {1, 2, 3, 4};
        System.out.println(b);
        List<Integer> c = Arrays.asList(b);
        System.out.println(c);
        Vector<Integer> d = new Vector<>(c);
        System.out.println(d);
    }
}

输出:

[I@123a439b
[Ljava.lang.Integer;@7de26db8
[1, 2, 3, 4]
[1, 2, 3, 4]

二维容器的直接打印

import java.util.*;
public class main {
    public static void main(String[] args) {
        Integer[][] arrays = {{1, 2}, {3, 4}};

        List<List<Integer>> list = new ArrayList<>();
        for (Integer[] array1D : arrays) {
           list.add(new ArrayList<>(Arrays.asList(array1D)));
        }

        Vector<Vector<Integer>> vector = new Vector<>();
        for (Integer[] array1D : arrays) {
           vector.add(new Vector<>(Arrays.asList(array1D)));
        }

        System.out.println(list);
        System.out.println(vector);
    }
}

输出:

[[1, 2], [3, 4]]
[[1, 2], [3, 4]]

普通数组的转化

也非常方便,有现成的Arrays.toString()函数可用,二维及以上数组则要用deepToString()。不需要循环遍历就能实现,如需要的话请参考上面go语言中的遍历实现方法。

import java.util.*;
public class main {
    public static void main(String[] args) {
        Integer[] array1D = {1, 2, 3, 4};
        Integer[][] array2D = {{1, 2}, {3, 4}};
        int[][][] array3D = {{{1, 2}, {3, 4}}, {{11, 12}, {13, 14}}};

        String str1 = Arrays.toString(array1D);
        String str2 = Arrays.deepToString(array2D);
        String str3 = Arrays.deepToString(array3D);

        System.out.println(str1);
        System.out.println(str2);
        System.out.println(str3);
    }
}

输出:

[1, 2, 3, 4]
[[1, 2], [3, 4]]
[[[1, 2], [3, 4]], [[11, 12], [13, 14]]]


C++

C++98开始有vector容器,但在C++中容器和数组都不能被直接打印。

遍历方法与golang中的基本相同:

一维容器的遍历

1. to_string()

#include <vector>
#include <sstream>
#include <iostream>
using namespace std;
int main() {
    vector<int> v = {1, 2, 3, 4, 5};
    string str = "[";
    for (int i = 0; i < v.size(); ++i) {
        str += to_string(v[i]);
        if (i != v.size() - 1) {
            str += ", ";
        }
    }
    str += "]";
    cout << str << endl;
    return 0;
}

2. stringstream

#include <vector>
#include <sstream>
#include <iostream>
using namespace std;
int main() {
    vector<int> v = {1, 2, 3, 4, 5};
    stringstream ss;
    ss << "[";
    for (int i = 0; i < v.size(); ++i) {
        ss << v[i];
        if (i != v.size() - 1) {
            ss << ", ";
        }
    }
    ss << "]";
    cout << ss.str() << endl;
    return 0;
}

数组也能直接遍历,或者先把 array转vector 再遍历:

int arr[] = {1, 2, 3, 4, 5};
std::vector<int> vec(std::begin(arr), std::end(arr));

二维容器的遍历

#include <vector>
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main()
{
    vector<vector<int>> vec2d = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    stringstream ss;
    ss << "[";
    for (int i = 0; i < vec2d.size(); ++i) {
        ss << "[";
        for (int j = 0; j < vec2d[i].size(); ++j) {
            ss << vec2d[i][j] << ", ";
        }
        ss.seekp(-2, ios_base::end); //省掉判断:j==vec2d[i].size()-1 
        ss << "], ";
    }
    ss.seekp(-2, ios_base::end); //省掉判断:i==vec2d.size()-1 
    ss << "]";
    cout << ss.str() << endl;
    return 0;
}

使用copy()省掉for循环:

#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
#include <sstream>
using namespace std;

int main()
{
    vector<int> vec1d = {1, 2, 3, 4, 5};
    copy(vec1d.begin(), vec1d.end(), ostream_iterator<int>(cout, " "));
    cout << endl;
    
    stringstream ss;
    ss << "[";
    copy(vec1d.begin(), vec1d.end(), ostream_iterator<int>(ss, ","));
    ss.seekp(-1, ios_base::end);
    ss << "]";
    cout << ss.str() << endl;
    return 0;
}

都写成转换函数:

#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
#include <sstream>
using namespace std;

string VectorToString(vector<int> vec, string sep = ",")
{
    stringstream ss;
    ss << "[";
    copy(vec.begin(), vec.end(), ostream_iterator<int>(ss, sep.c_str()));
    ss.seekp(-(int)sep.size(), ios_base::end);
    ss << "]";
    return ss.str();
}

string Vector2dToString(vector<vector<int>> vec2d, string sep = ",")
{
    stringstream ss;
    ss << "[";
    for (int i = 0; i < vec2d.size(); ++i) {
        ss << "[";
        copy(vec2d[i].begin(), vec2d[i].end(), ostream_iterator<int>(ss, sep.c_str()));
        ss.seekp(-(int)sep.size(), ios_base::end);
        ss << "]" << sep;
    }
    ss.seekp(-(int)sep.size(), ios_base::end);
    ss << "]";
    return ss.str();
}

int main()
{
    vector<int> vec1d = {1, 2, 3, 4, 5};
    vector<vector<int>> vec2d = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    cout << VectorToString(vec1d) << endl;
    cout << Vector2dToString(vec2d) << endl;
    cout << VectorToString(vec1d, ", ") << endl;
    cout << Vector2dToString(vec2d, ", ") << endl;
    return 0;
}

输出:

[1,2,3,4,5]
[[1,2,3],[4,5,6],[7,8,9]]
[1, 2, 3, 4, 5]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]


简要小结

本文主要介绍了在 Python、Golang、Java 和 C++ 这些常见的编程语言中,数组/容器转化为字符串的方法。

在 Python 中,可以通过 for 循环或者列表推导式来遍历数组或列表,并通过 join() 方法将其转化为字符串。

在 Golang 中,可以使用 for 循环或 range 关键字和切片操作符进行一维和二维数组的遍历,并通过 fmt 包中的 Sprintf() 函数将其转化为字符串。

在 Java 中,可以使用 foreach 循环进行一维和二维数组的遍历,并使用 Arrays.toString() 函数将一维数组转化为字符串,使用 Arrays.deepToString() 函数将二维数组转化为字符串。

在 C++ 中,可以使用 for 循环、迭代器和 range 循环等多种方法进行一维和二维容器的遍历,并通过 std::to_string() 函数和 std::stringstream 类将容器转化为字符串。

标签: python golang java

本文转载自: https://blog.csdn.net/boysoft2002/article/details/130437247
版权归原作者 Hann Yang 所有, 如有侵权,请联系我们删除。

“浅谈Golang等多种语言转数组成字符串”的评论:

还没有评论