逐行打印嵌套列表 - Python [英] Print a nested list line by line - Python
问题描述
我正在尽力打印 A
的形式:
1 2 3
2 3 4
4 5 6
那是不一样的,但是如果没有所有的元素,我就不能这样做。这是我的代码到目前为止:
for r in A:
for t in r:
print (t,)
print
这是我的输出:
1
2
3
2
3
4
4
5
6
看起来很简单,我想稍作改动它。感谢!
使用简单的for循环和 示例: 这里的区别是我们可以支持任意长度的内部列表。 / p> 你的例子没有像预期的那样工作的原因是因为你的内部循环遍历子列表的每个元素;对于A中的r, 和 但是 I am trying my best to print That is in different lines, but I am unable to do so without all the elements in different lines. This is my code so far: This is my output: It seems really simple, and I think a minor change would do it. Thanks! Use a simple for loop and Example: The difference here is that we can support arbitrary lengths of inner lists. The reason your example did not work as expected is because your inner loop is iterating over each element of the sub-list; And But 这篇关于逐行打印嵌套列表 - Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!.join()
使用 map()将嵌套列表中的每个
int
映射到 str
code $。
>>> ys = [[1,2,3],[4,5,6],[7,8,9,10]]
>>>对于xs in ys:
... print(.join(map(str,xs)))
...
1 2 3
4 5 6
7 8 9 10
:#r = [1,2,3]
for t in r:#t = 1(第一次迭代)
print(t,)
print
print()
默认情况下会在最后打印换行符,除非您使用: print(end =)
我相信如果你使用的是Python 2.x print t,那么
可以工作。例如:
>>> ys = [[1,2,3],[4,5,6],[7,8,9,10]]
>>> for xs in ys:
... for x in xs:
... print x,
... print
...
1 2 3
4 5 6
7 8 9 10
print(x,)
不会按照您的意图工作; Python 2.x或3.x A = [[1, 2, 3], [2, 3, 4], [4, 5, 6]]
A
of the form:1 2 3
2 3 4
4 5 6
for r in A:
for t in r:
print(t,)
print
1
2
3
2
3
4
4
5
6
" ".join()
mapping each int
in the nested list to a str
with map()
.>>> ys = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
>>> for xs in ys:
... print(" ".join(map(str, xs)))
...
1 2 3
4 5 6
7 8 9 10
for r in A: # r = [1, 2, 3]
for t in r: # t = 1 (on first iteration)
print(t,)
print
print()
by default prints new-line characters at the end unless you use: print(end="")
I believe if you were using Python 2.x print t,
would work. For example:>>> ys = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
>>> for xs in ys:
... for x in xs:
... print x,
... print
...
1 2 3
4 5 6
7 8 9 10
print(x,)
would not work as you intended it; Python 2.x or 3.x