Python打印输出数组中全部元素 您所在的位置:网站首页 python依次输出数组中的元素 Python打印输出数组中全部元素

Python打印输出数组中全部元素

2023-03-26 03:57| 来源: 网络整理| 查看: 265

学习Python的人都知道数组是最常用的的数据类型,为了保证程序的正确性,需要调试程序。

因此,需要在程序中控制台中打印数组的全部元素,如果数组的容量较小,例如 只含有10个元素,采用print命令或print函数可以答应出数组中的每个元素;

如果数组的容量过大,只能打印出数组的部分元素,打印结果只包含开始部分元素和结尾部分元素,中间元素省略。省略的部分不利于程序的调试;

因此,为了方便调试程序,需要将数组中的元素全部打印出来。

1. 少量元素情况

#打印数组中的元素 import numpy as np a = np.array(6) print a

程序结果为:

[0 1 2 3 4 5]

2. 大量元素情况

可以采用 set_printoptions(threshold='nan')

import numpy as np np.set_printoptions(threshold=np.NaN) print np.arange(100) print np.arange(100).reshape(10, 10)

结果为:

[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24  25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49  50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74  75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99] [[ 0  1  2  3  4  5  6  7  8  9]  [10 11 12 13 14 15 16 17 18 19]  [20 21 22 23 24 25 26 27 28 29]  [30 31 32 33 34 35 36 37 38 39]  [40 41 42 43 44 45 46 47 48 49]  [50 51 52 53 54 55 56 57 58 59]  [60 61 62 63 64 65 66 67 68 69]  [70 71 72 73 74 75 76 77 78 79]  [80 81 82 83 84 85 86 87 88 89]  [90 91 92 93 94 95 96 97 98 99]]

当array里面的存放的数据维度过大时,在控制台会出现不能将array完全输出的情况,中间部分的结果会用省略号打印出来。这时就需要用到numpy里面的set_printoptions()方法

我们来看一下 set_printoptions 方法的简单说明

set_printoptions(precision=None, threshold=None, edgeitems=None, linewidth=None, suppress=None, nanstr=None, infstr=None, formatter=None)

precision:输出结果保留精度的位数

threshold:array数量的个数在小于threshold的时候不会被折叠

edgeitems:在array已经被折叠后,开头和结尾都会显示edgeitems个数

formatter:这个很有意思,像python3里面str.format(),就是可以对你的输出进行自定义的格式化

举例:

precision:

np.set_printoptions(precision=4) print(np.array([1.23456789])) >> [ 1.2346] # 最后进位了

threshold:

np.set_printoptions(threshold=10) print(np.arange(1, 11, 1)) # np.arange(1, 11, 1)生成出来是[1-10],10个数 >> [ 1 2 3 4 5 6 7 8 9 10] np.set_printoptions(threshold=9) print(np.arange(1, 11, 1)) >> [ 1 2 3 ..., 8 9 10]

edgeitems:

np.set_printoptions(threshold=5) print(np.arange(1, 11, 1)) >> [ 1 2 3 ..., 8 9 10] np.set_printoptions(threshold=5, edgeitems=4) print(np.arange(1, 11, 1)) >> [ 1 2 3 4 ..., 7 8 9 10]

formatter

np.set_printoptions(formatter={'all': lambda x: 'int: ' + str(-x)}) print(np.arange(1, 5, 1)) >> [int: -1 int: -2 int: -3 int: -4]

这个formatter是一个可调用的字典,'all'是其中一个key,表示里面的x可以包含所有type,还有其他key,具体可以在源码里面查看最后如果只想在代码中的某一部分使用自定义的printoptions,那么可以通过再次调用np.set_printoptions()这个方法来进行reset

您可能感兴趣的文章:python 以16进制打印输出的方法在Python中分别打印列表中的每一个元素方法Python打印“菱形”星号代码方法python打印n位数“水仙花数”(实例代码)使用python打印十行杨辉三角过程详解Python利用for循环打印星号三角形的案例python随机打印成绩排名表


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有