如何在一行中打印二维数组的行?
How can I print the rows of a 2D-array in one line?
我需要像 [[A,B],[C,D]]
一样打印二维数组 A B C D
。
我见过很多使用 ''.join()
打印一维数组的方法,但没有看到二维数组的方法。我该怎么做?
您需要将二维数组 "flatten" 转换为一维列表,然后可以使用您已经提到的方法 (' '.join(mylist)
)。无需借助像 Numpy 这样的库,使用 chain.from_iterable
from the built-in itertools
模块最容易实现扁平化:
import itertools as it
x = [['a','b'],['c','d']]
print(' '.join(it.chain.from_iterable(x)))
我需要像 [[A,B],[C,D]]
一样打印二维数组 A B C D
。
我见过很多使用 ''.join()
打印一维数组的方法,但没有看到二维数组的方法。我该怎么做?
您需要将二维数组 "flatten" 转换为一维列表,然后可以使用您已经提到的方法 (' '.join(mylist)
)。无需借助像 Numpy 这样的库,使用 chain.from_iterable
from the built-in itertools
模块最容易实现扁平化:
import itertools as it
x = [['a','b'],['c','d']]
print(' '.join(it.chain.from_iterable(x)))