python逐行打印,逐行打印嵌套列表 - Python

A = [[1, 2, 3], [2, 3, 4], [4, 5, 6]]

I am trying my best to print A of the form:

1 2 3

2 3 4

4 5 6

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:

for r in A:

for t in r:

print(t,)

print

This is my output:

1

2

3

2

3

4

4

5

6

It seems really simple, and I think a minor change would do it. Thanks!

解决方案

Use a simple for loop and " ".join() mapping each int in the nested list to a str with map().

Example:

>>> 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

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;

for r in A: # r = [1, 2, 3]

for t in r: # t = 1 (on first iteration)

print(t,)

print

And 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

But print(x,) would not work as you intended it; Python 2.x or 3.x

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值