如何用Python打印数组?

2024-04-25 01:25:40 发布

您现在位置:Python中文网/ 问答频道 /正文

在C++中,我有下面的代码,我希望在Python中实现同样的代码。你知道吗

#include iostream
using namespace std;

int main()

{

    int tab[10][10], m, n, i, j;

    cout << "\n number of rows n = ";
    cin >> n;
    cout << "\n number of columns m = ";
    cin >>m;
    for (int i=0; i<n; i++)
    {
        for (int j=0; j<m; j++)
        {
            cout << "\n tab[" << i << "][" << j << "] = ";
            cin >> tab[i][j];
        }
    }
    cout << endl;
    for (int i=0; i<n; i++)
    {
        for (int j=0; j<m; j++)
            cout << "\t\t" << tab[i][j];
            cout << "\n\n";
    }
    return 0;
}

我试过这个:

def main():
    pass
    tab = []
    m = input ("Numbers of rows: ")
    n = input ("Numbers of columns: ")
    for i in xrange(m):
        for j in xrange(n):
            print tab[i:j], "= "
            arr = input ("tab[i:j]")
            print arr

我不知道如何在for循环中打印tab[i][j] = "value input from keyboard"


Tags: columnsof代码innumberforinputmain
1条回答
网友
1楼 · 发布于 2024-04-25 01:25:40

python中没有类似iostreams的实现。也没有多维数组。 你会用 r=原始输入(“文本:”)

请求用户的参数。你知道吗

 #!/usr/bin/env python

 # untested python code!

 n = int(raw_input("number of rows, n = "))
 m = int(raw_input("number of cols, m = "))

 tab = [[0]*n for i in xrange(m)] # generates [[0, 0, .. 0][0, 0, .. 0]...[0, .., 0]]

 for i in range(0, n):
     for j in range(0, m):
        tab[i][j] = int(raw_input("tab[%d][%d] = "%(i, j) ))

 for i in range(0, n):
     for j in range(0, m):
        print "\t\t%d" % tab[i][j]
     print "\n"

建议对数组使用numpy之类的东西。有更好的解决方案,如哈希或字典。你知道吗

编辑: 正如我上面所设想的:您需要首先通过

tab = [[0]*n for i in xrange(m)]

初始化之后,通过写入

print tab

将显示整个结构。单个元素的调用方式如下:

print tab[i][j]

使用冒号(:)指定一个范围,制表符[i][j]!=tab[i:j]

您仍然可以打印一行

print tab[i]  # <  only the first array in the array
print tab[i][j] # <  only the element j. element in the i. array

干杯。你知道吗

相关问题 更多 >