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

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

问题描述

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

我正在尽力打印表单的A:

1 2 32 3 44 5 6

那是在不同的行中,但是如果没有不同行中的所有元素,我将无法这样做.到目前为止,这是我的代码:

 for r in A:对于 r 中的 t:打印(吨,)打印

这是我的输出:

123234456

这看起来真的很简单,我认为稍微改变一下就可以了.谢谢!

解决方案

使用简单的 for 循环和 " ".join() 映射嵌套列表中的每个 int到带有 map()str.

示例:

<预><代码>>>>ys = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]>>>对于 ys 中的 xs:... 打印(" ".join(map(str, xs)))...1 2 34 5 67 8 9 10

这里的区别在于我们可以支持任意长度的内部列表.

<小时>

您的示例未按预期工作的原因是您的内部循环正在迭代子列表的每个元素;

for r in A: # r = [1, 2, 3]for t in r: # t = 1 (第一次迭代)打印(吨,)打印

并且 print() 默认情况下会在末尾打印换行符,除非您使用: print(end="") 我相信如果您使用的是 Python 2.x print t, 会起作用.例如:

<预><代码>>>>ys = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]>>>对于 ys 中的 xs:... 对于 x 中的 x:... 打印 x,... 打印...1 2 34 5 67 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天全站免登陆