python学习笔记

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

3. 

#coding: utf-8
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np 

mnist = input_data.read_data_sets("MINST_data/", one_hot=True)

for i in range(20):
    one_hot_label = mnist.train.labels[i, :]
    label = np.argmax(one_hot_label)
    # mnist_train_0.jpg label: 7
    print('mnist_train_%d.jpg label: %d' % (i, label))
原文地址:https://www.cnblogs.com/Joyce-song94/p/7142050.html