温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用Python怎么打印输出数组中的全部元素

发布时间:2021-04-30 16:27:34 来源:亿速云 阅读:4728 作者:Leah 栏目:开发技术

这篇文章给大家介绍使用Python怎么打印输出数组中的全部元素,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

Python主要用来做什么

Python主要应用于:1、Web开发;2、数据科学研究;3、网络爬虫;4、嵌入式应用开发;5、游戏开发;6、桌面应用开发。

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]

关于使用Python怎么打印输出数组中的全部元素就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI