逐行打印嵌套列表 - Python [英] Print a nested list line by line - Python

查看:411
本文介绍了逐行打印嵌套列表 - Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我正在尽力打印 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循环和.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

这里的区别是我们可以支持任意长度的内部列表。 / p>




你的例子没有像预期的那样工作的原因是因为你的内部循环遍历子列表的每个元素;对于A中的r,

 :#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]]

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

这篇关于逐行打印嵌套列表 - Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆