Converting 2D String array into 1D String array in Python
本问题已经有最佳答案,请猛点这里访问。
我有一个像这样的字符串数组:
1 2 3 4 | string = [ ["this is a sample", "this is another sample"], ["The third sample", "the fourth one"] ] |
但我想把它转换为:
1 2 3 4 | string = [ "this is a sample", "this is another sample", "The third sample", "the fourth one" ] |
号
我该怎么做?我知道我可以通过预先分配一个字符串和迭代来实现。但是有没有更简单的方法呢?
也许使用列表理解。有点像
1 | string = [s for S in string for s in S] |
号
你可以使用列表理解来尝试这样做。代码:
1 2 3 4 5 6 | string = [ ["this is a sample", "this is another sample"], ["The third sample", "the fourth one"] ] print([_ for i in range(len(string)) for _ in string[i]]) |