Is there a way I can join a list of of lists, where the inner list are joined by spaces and the outer lists are joined by '\n'? Is it possible to do this in a single line?
Example input:
>>> a = [[1,2,3],[2,3,4]]
Desired output:
1 2 3
2 3 4
What I've tried:
>>> ' '.join([str(s) for s in [l for l in a]])
'[1, 2, 3] [2, 3, 4]'
>>> ' '.join([str(s) for s in [l.append('\n') for l in a]])
'None None'
>>> a = [[1,2,3],[2,3,4]]
>>> [l.append('\n') for l in a]
>>> ' '.join([str(s) for s in [l for l in a]])
"[1, 2, 3, '\\n'] [2, 3, 4, '\\n']"
答案 0 :(得分:2)
您需要使用两个连接函数。
'\n'.join(' '.join(str(j) for j in i) for i in a)
示例:
>>> print('\n'.join(' '.join(str(j) for j in i) for i in a))
1 2 3
2 3 4
>>>
答案 1 :(得分:2)
怎么样:
print '\n'.join([' '.join([str(i) for i in b]) for b in a])
答案 2 :(得分:1)
试试这个 -
print('\n'.join([' '.join(map(str, x)) for x in a]))
这使用'\n'
加入子列表,使用' '
(空格)加入内部列表中的每个元素。
示例/演示 -
>>> a = [[1,2,3],[2,3,4]]
>>> print('\n'.join([' '.join(map(str, x)) for x in a]))
1 2 3
2 3 4