python中的等价C ++嵌套打印

时间:2011-01-11 02:10:35

标签: c++ python printing nested-loops equivalent

我正在尝试在python中运行这个C ++语句,而我在将循环放置到循环中时遇到了麻烦。

for (int i = 0; i < 3; i++)
{
    for (int j = 0; j < 3; j++)
    {
        for (int k = 0; k < 3; k++)
        {
          cout<<_3x3x3[i][j][k]<<" ";
        }
    }
     //print here in python
     cout<<endl;
}

在python中:

_3x3x3 = [[[0 for col in range(3)] for row in range(3)] for depth in range(3)]

for i in range(3):
    for j in range(3):
        for k in range(3):
            _3x3x3[i][j][k] = 1

for col in _3x3x3:
    print col
print
for row in _3x3x3:
    print row
print
for depth in _3x3x3:
    print depth
#I want to print this in the C++ style above
for i in range(3):
    for j in range(3):
        for k in range(3):
            print _3x3x3[i][j][k]

2 个答案:

答案 0 :(得分:4)

for i in range(3):
    for j in range(3):
        for k in range(3):
            # something here
            print _3x3x3[i][j][k],
    print

答案 1 :(得分:0)

为了多样化和面向未来:

from __future__ import print_function

for i in range(3):
    print(*(_3x3x3[i][j][k] for j in range(3) for k in range(3)))

这与C ++代码的区别在于,它不会在换行符之前的每一行末尾输出空格。不过,这可能是一件好事。