python学习笔记1-numpy/enumerate

1. np.size和np.prod

1 import numpy as np
2 x = np.zeros((3, 5,  2), dtype=np.complex128)
3 # ndarray.size is the number of elements in the array
4 # equivalent to np.prod(a.shape)
5 print(x.size)
6 print(np.prod(x.shape))

2. enumerate()函数是python的内置函数,在字典上进行枚举、列举,对于一个可迭代的(iterable)/可遍历的对象,enumerate将其组成一个索引序列,利用它可以同时获得索引和值。注:enumerate多用于for循环中得到计数。

使用举例:

(1)对于列表,既要遍历索引又要遍历元素时

1 list1 = ["", "", "一个", "测试"]
2 # method 1
3 for i in range(len(list1)):
4     print(i, list1[i])
5 # method 2 use enumerate
6 for index, item in enumerate(list1):
7     print(index, item)

(2)enumerate还可以接收第二个参数,用于指定索引起始值

1 list1 = ["", "", "一个", "测试"]
2 for index, item in enumerate(list1, 1):
3     print(index, item)
4 '''
5 1 这
6 2 是
7 3 一个
8 4 测试
9 '''

(3)enumerate用于统计文件行数

1 # method 1
2 count = len(open(filepath, 'r').readlines())
3 # method 2
4 count = -1
5 for index, line in enumerate(open(filepath, 'r')):
6     count += 1

 

转载于:https://www.cnblogs.com/Joyce-song94/p/7142050.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值