【问题标题】:How I print an array in Python?如何在 Python 中打印数组?
【发布时间】:2014-11-12 17:48:11
【问题描述】:

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

【问题讨论】:

  • 到目前为止你尝试过什么?
  • 堆栈溢出不是代码翻译服务。
  • 用python写这段代码真的很简单,大功告成!
  • coutcin 是 C++ 结构,在 Python 中没有等价物,因为 Pyhton 是一种高级语言。
  • 您是否也想包含缓冲区溢出错误?这在 Python 中可能有点困难。

标签: python arrays


【解决方案1】:

在 python 中没有像 iostreams 这样的实现。也没有多维数组。 你会用 r = raw_input("文本:")

请求用户的参数。

 #!/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]

使用冒号 (:) 指定范围,tab[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

干杯。

【讨论】:

  • 为什么不使用nm 来动态调整tab 列表的大小而不是硬编码为10?
  • mn 需要转换为 int 才能在range() 中使用,否则它已经足够接近 OP 的 C++ 版本了。
猜你喜欢
  • 2016-11-27
  • 1970-01-01
  • 1970-01-01
  • 2017-08-10
  • 2011-09-19
  • 2013-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多