20条非常实用的Python代码,建议收藏!

100个Python代码大全:学完这篇从Python小白到架构师 Python是一种广泛使用的高级编程语言,以其简洁优雅、易于学习和强大的库而闻名。无论你是一位经验丰富的程序员还是初学者,都可以从这种语言的丰富资源中受益。在本篇博客中,我将分享100个实用的Python代码示例,旨在帮助你掌握Python编程,并在日常工作中提高效率。 阅读详情

据说Python之父-Guido Van Rossum打算让CPython更快,速度直接翻五倍,这是实实在在的好消息。

Python一直以来被诟病速度慢,影响开发效率,希望这次Guido老爷子能帮python打一场漂亮的翻身仗。

这篇文章不准备介绍Python速度如何,而是给大家带来一些常用且实用的Python代码实例,几乎是开发者必备的知识点。

1、合并两个字典

Python3.5之后,合并字典变得容易起来。我们可以通过**符号解压字典,并将多个字典传入{}中,实现合并。

def Merge(dict1, dict2): 
    res = {**dict1, **dict2} 
    return res 
      
# 两个字典
dict1 = {"name": "Joy", "age": 25}
dict2 = {"name": "Joy", "city": "New York"}
dict3 = Merge(dict1, dict2) 
print(dict3)

输出:

{'name': 'Joy', 'age': 25, 'city': 'New York'}

2、链式比较

python有链式比较的机制,在一行里支持多种运算符比较。相当于拆分多个逻辑表达式,再进行逻辑与操作。

a = 5

print(2 < a < 8)
print(1 == a < 3)

输出:

True
False

3、重复打印字符串

将一个字符串重复打印多次,一般使用循环实现,但有更简易的方式可以实现。

n = 5
string = "Hello!"

print(string * n)

输出:

Hello!Hello!Hello!Hello!Hello!

4、检查文件是否存在

我们知道Python有专门处理系统交互的模块-os,它可以处理文件的各种增删改查操作。

那如何检查一个文件是否存在呢?os模块可以轻松实现。

from os import path

def check_for_file():
    print("Does file exist:", path.exists("data.csv"))

if __name__=="__main__":
    check_for_file()

输出:

Does file exist: False

5、检索列表最后一个元素

在使用列表的时候,有时会需要取最后一个元素,有下面几种方式可以实现。

my_list = ['banana', 'apple', 'orange', 'pineapple']

#索引方法
last_element = my_list[-1]

#pop方法
last_element = my_list.pop()

输出:

'pineapple'

6、列表推导式

列表推导式是for循环的简易形式,可以在一行代码里创建一个新列表,同时能通过if语句进行判断筛选

def get_vowels(string):
    return [vowel for vowel in string if vowel in 'aeiou'] 

print("Vowels are:", get_vowels('This is some random string'))

输出:

Vowels are:  ['i', 'i', 'o', 'e', 'a', 'o', 'i']

7、计算代码执行时间

python中time模块提供了时间处理相关的各种函数方法,我们可以使用它来计算代码执行的时间。

import time

start_time = time.time()

total = 0
for i in range(10):
  total += i
print("Sum:", total)

end_time = time.time()
time_taken = end_time - start_time
print("Time: ", time_taken)

输出:

Sum: 45
Time:  0.0009975433349609375

8、查找出现次数最多的元素

使用max方法找出列表中出现次数最多的元素。

def most_frequent(list):
  return max(set(list), key=list.count)

mylist = [1,1,2,3,4,5,6,6,2,2]
print("出现次数最多的元素是:", most_frequent(mylist))

输出:

出现次数最多的元素是: 2

9、将两个列表转换为字典

有两个列表,将列表A里的元素作为键,将列表B里的对应元素作为值,组成一个字典。

def list_to_dictionary(keys, values):
  return dict(zip(keys, values))

list1 = [1, 2, 3]
list2 = ['one', 'two', 'three']

print(list_to_dictionary(list1, list2))

输出:

{1: 'one', 2: 'two', 3: 'three'}

10、异常处理

Python提供了try...except...finally的方式来处理代码异常,当然还有其他组合的方式。

a, b = 1,0

try:
    print(a/b)
except ZeroDivisionError:
    print("Can not divide by zero")
finally:
    print("Executing finally block")

输出:

Can not divide by zero
Executing finally block

11、反转字符串

使用切片操作对字符串进行反转,这是比较直接有效的方式。这也可以用来检测回文数。

str = "Hello World"

print("反转后字符串是:", str[::-1])

输出:

反转后字符串是: dlroW olleH

12、字符串列表组成单个字符串

使用join方法将字符串列表组成单个字符串。

list = ["Hello", "world", "Ok", "Bye!"]
combined_string = " ".join(list)

print(combined_string)

输出:

Hello world Ok Bye!

13、返回字典缺失键的默认值

字典中的get方法用于返回指定键的值,如果键不在字典中返回默认值 None 或者设置的默认值。

dict = {1:'one', 2:'two', 4:'four'}

#returning three as default value
print(dict.get(3, 'three'))

print("原始字典:", dict) 

输出:

three
原始字典: {1: 'one', 2: 'two', 4: 'four'}

14、交换两个变量的值

在不使用临时变量的前提下,交换两个变量的值。

a, b = 5, 10

# 方法1
a, b = b, a

# 方法2
def swap(a,b):
  return b,a
swap(a,b)

15、正则表达式

正则表达式用来匹配处理字符串,python中的re模块提供了全部的正则功能。

import re

text = "The rain in spain"
result = re.search("rain", text)

print(True if result else False)

输出:

True

16、筛选值

python中的filter方法可以用来进行值的筛选。

my_list = [0,1,2,3,6,7,9,11]

result = filter(lambda x: x % 2!=0, my_list)

print(list(result))

输出:

[1, 3, 7, 9, 11]

17、统计字频

判断字符串每个元素出现的次数,可以用collections模块中的Counter方法来实现,非常简洁。

from collections import Counter
result = Counter('banana')
print(result)

输出:

Counter({'a': 3, 'n': 2, 'b': 1})

18、变量的内存占用

如何输出python中变量的内存占用大小,可以通过sys模块来实现。

import sys

var1 = 15
list1 = [1,2,3,4,5]

print(sys.getsizeof(var1))
print(sys.getsizeof(list1))

输出:

28
104

19、链式函数调用

在一行代码中调用多个函数。

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

a, b = 5, 10

print((add if b > a else subtract)(a,b))

输出:

15

20、从列表中删除重复项

删除列表中重复项一般可以通过遍历来筛选去重,或者直接使用集合方法。

list1 = [1,2,3,3,4,'John', 'Ana', 'Mark', 'John']

# 方法1
def remove_duplicate(list_value):
    return list(set(list_value))
print(remove_duplicate(list1))

# 方法2
result = []
[result.append(x) for x in list1 if x not in result]
print(result)

输出:

[1, 2, 3, 4, 'Ana', 'John', 'Mark']
[1, 2, 3, 4, 'John', 'Ana', 'Mark']



推荐阅读:
入门: 最全的零基础学Python的问题  | 零基础学了8个月的Python  | 实战项目 |学Python就是这条捷径
干货:爬取豆瓣短评,电影《后来的我们》 | 38年NBA最佳球员分析 |   从万众期待到口碑扑街!唐探3令人失望  | 笑看新倚天屠龙记 | 灯谜答题王 |用Python做个海量小姐姐素描图 |碟中谍这么火,我用机器学习做个迷你推荐系统电影
趣味:弹球游戏  | 九宫格  | 漂亮的花 | 两百行Python《天天酷跑》游戏!
AI: 会做诗的机器人 | 给图片上色 | 预测收入 | 碟中谍这么火,我用机器学习做个迷你推荐系统电影
小工具: Pdf转Word,轻松搞定表格和水印! | 一键把html网页保存为pdf!|  再见PDF提取收费! | 用90行代码打造最强PDF转换器,word、PPT、excel、markdown、html一键转换 | 制作一款钉钉低价机票提示器! |60行代码做了一个语音壁纸切换器天天看小姐姐!|

年度爆款文案

点阅读原文,领AI全套资料!
11个实用又简洁的Python短代码,建议收藏 普通程序员写的代码和大神写的代码的最大区别就是我们是用代码堆砌功能,很少注重代码品质和效率,而大神们能写出优雅精简的代码,实现一个功能我们需要几十上百行代码,而他们可能一行就解决了!并且他们的代码运行效率还比你高!今天给大家分享一些常用的Python高效代码片段,希望可以给大家的代码质量带来一点点提高! 阅读详情

相关推荐

20条非常实用的Python代码实例

据说Python之父-Guido Van Rossum打算让CPython更快,速度直接翻五倍,这是实实在在的好消息。Python一直以来被诟病速度慢,影响开发效率,希望这次Guido老爷子能帮python打一场漂亮的翻身仗。 这篇文章不准备介绍Python速度如何,而是给大家带来一些常用且实用的Python代码实例,几乎是开发者必备的知识点。 1、合并两个字典 Python3.5之后,合并字典变得容易起来。我们可以通过**符号解压字典,并将多个字典传入{}中,实现合并。 def Merge(dict1,

xilu_data的博客 2050

python代码大全

python代码大全

zy0412326的专栏 3万+

25条很棒的Python一行代码,建议收藏!

自从我用Python编写第一行代码以来,就被它的简单性、出色的可读性和特别流行的一行代码所吸引。 在下面,我将给大家介绍并解释一些Python一行程序。 可能有些你还不知道,但对你未来的Python项目很有用。 1、交换两个变量 # a = 4 b = 5 a,b = b,a # print(a,b) >> 5,4 让我们通过交换两个变量作为一个简单的开始。 此方法是最简单、最直观的方法之一,无需使用临时变量或应用算术操作即可编写。 2、多个变量赋值 a,b,c = 4,5.5,'Hello'

weixin_46737755的博客 1520

极简 Python:10 段代码,学会基础 python

本篇共包含 10 段简单的 Python,涉及常用语法和常用库(但毫无疑问删减了很多,比如没有字典)任何不懂的地方可直接留言~注:如果某个地方以 “#” 开始意思是:这是注释。

2401_85339817的博客 4820

Python浪漫星空(完整代码)

Python绘制一个含有月亮、流星、星星的炫酷星空的完整代码。

AIGC 2万+

Windows系统监控实战:Grafana+Prometheus+node_exporter保姆级配置指南(含常见问题解决)

本文提供了一份详尽的Windows系统监控实战指南,详细讲解了如何从零部署Grafana、Prometheus和node_exporter(实际为windows_exporter)监控栈。内容涵盖核心组件认知、分步配置解析、高级生产环境考量,并重点针对配置过程中常见的“No Data”问题提供了系统性的排查手册,旨在帮助用户快速搭建稳定可靠的系统资源监控平台。

weixin_29197835的博客 1008

20 条非常实用的 Python 代码,建议收藏!

据说Python之父-Guido Van Rossum打算让CPython更快,速度直接翻五倍,这是实实在在的好消息。 Python一直以来被诟病速度慢,影响开发效率,希望这次Guido老爷子能帮python打一场漂亮的翻身仗。 这篇文章不准备介绍Python速度如何,而是给大家带来一些常用且实用的Python代码实例,几乎是开发者必备的知识点。 1、合并两个字典 Python3.5之后,合并字典变得容易起来。我们可以通过**符号解压字典,并将多个字典传入{}中,实现合并。 defMe..

XMWS-IT 530

Spring Boot整合AWS S3文件上传实战:从配置到权限管理全流程解析

本文详细解析了Spring Boot整合AWS S3文件上传的全流程,包括基础配置、核心上传功能实现、高级权限控制及安全最佳实践。通过实战案例展示如何高效处理文件上传、大文件分片及权限管理,帮助开发者构建健壮的文件管理系统。特别强调AWS S3的高可用性和安全性,适用于企业级应用开发。

sam99的博客 283

收藏!20条非常实用的Python代码实例

在使用列表的时候,有时会需要取最后一个元素,有下面几种方式可以实现。#索引方法#pop方法。

分享Python、数据分析、人工智能前沿知识 546

【Apollo规划模块探秘】—— 场景(Scenario)驱动的决策引擎

本文深入解析了Apollo自动驾驶平台规划模块的核心机制——场景(Scenario)驱动的决策引擎。文章通过类比日常驾驶,阐述了规划模块如何像经验丰富的司机一样,根据不同的路况(如车道跟随、无保护左转)切换不同的“驾驶模式”。重点剖析了场景管理器(ScenarioManager)如何基于感知信息进行场景判断与切换,以及“场景-阶段-任务”双层状态机如何精密协作,实现灵活、高效且安全的轨迹规划。

rnn9storyteller的博客 278

Vue - 超强实现网页禁止浏览器缩放功能,浏览器缩放时保持网页不变形、元素不会被挤压等,屏蔽浏览器鼠标滚轮缩放页面(提供详细示例代码,一次引入整个网站无人可以搞乱你的页面布局及样式)

vue,nuxt,禁止浏览器缩放,如何用户缩放浏览器导致页面变形,网页缩放后页面变形了怎么办,怎么解决网站被缩放后元素乱套错乱,vue怎么禁止网页不被缩放,vue如何禁止浏览器缩放,vue缩放网页变形影响布局怎么办,vue电脑分辨率及缩放导致页面变形的问题,前端页面解决浏览器或者系统被放大和缩小导致的显示问题,Vue中页面自适应缩放,如何防止Vue页面缩放时变形/调整大小,Vue项目中,防止页面被缩放和放大,vue等比例缩放网页,网页缩放后界面变形咋办,禁止页面缩放,vue禁止浏览器改变窗口大小,Vue项目

🏆 前端领域优质创作者 1万+

50条有趣的Python一行代码,建议收藏!

大家好,我是小F。在学习Python的过程中,总会发现Python能够轻易的解决许多问题。一些复杂的任务,甚至可以使用一行Python代码就能搞定。下面,小F给大家介绍50个有趣的Pyth...

法纳斯特 4845

【GameFramework框架内置模块】6、实体(Entity)

实体Entity就是一个实体的基本单元,类似于Unity的GameObject对象本体,然后这个本体上面附加其他各种各样组件,才能实现各种各样的功能。一般需要在游戏运行时动态加载的游戏对象,比如怪物、武器、子弹、特效,都需要给这个物体挂载一个实体Entity,这样的话就可以方便的对实例出来的对象进行管理。下面就来看一下如何使用吧。

优快云博客专家,Unity3D高级软件工程师,《Unity 3D从入门到实战》作者。 3137

20 条非常实用的 Python 代码,速速收藏

在使用列表的时候,有时会需要取最后一个元素,有下面几种方式可以实现。#索引方法#pop方法。

2201_75768457的博客 2775

Vins-Fusion 外参camera-imu 标定

Vins-Fusion是一种基于优化的多传感器状态估计器,一大特色是支持实时camera-imu外参校准(相机和IMU之间的旋转)。Vins-Fusion 外参camera-imu校准是利用两帧间计算相机位姿和imu预积分得到位姿,构建最小二乘问题,并通过SVD求解camera-imu外参旋转矩阵。

u010196944的博客 2490

【音视频】PJSIP库——示例简介、C++类说明

aectest音频回声消除测试工具,用于演示音频处理模块中的回声消除(AEC)功能,通常用于 VoIP 场景中优化语音质量。auddemo音频播放 / 录制演示,展示如何使用 PJProject 的音频接口进行基本的音频数据采集、播放和处理,例如波形显示或格式转换。stereotest立体声处理测试,可能用于演示多声道音频的处理方式,如混音、声道分离等。tonegen音频信号生成工具,用于生成测试用的音频信号(如正弦波、音调等),常用于音频设备测试或调试。recfile。

郭老二 434

90条写Python程序的建议,请收藏!

这是一位八年经验的 Python小伙伴总结的90条python建议,如果你也在学pythpn,或者准备要学习python,希望这篇文章对你有用。

WANGWUSAN66的博客 929

基于 SoC 的卷积神经网络车牌识别系统设计(1)引言

通过 CPU 软核 IP 在纯 FPGA 平台上构建一个 AI SoC 卷积神经网络车牌识别系统,其中,缩放、填充层、卷积层、ReLU、池化层、全连接层 IP 都是 Verilog 设计的,同时集成了各种高性能的 IP。这是最具挑战性的 AI SoC 芯片设计项目,集成了 Python 卷积神经网络代码、Verilog 卷积神经网络硬件设计、ARM SoC 设计、ARM 与 FPGA 的交叉编译流程等等。这不仅是科研学习、集创竞赛、秋招求职的一个极具优势的精彩项目,也是目前最火热的芯片行业之中的一个...

新芯设计的博客 3778

50 条实用的编写Python 程序建议

50 条实用的编写Python 程序建议,如果你要接触Python或准备要学习Python,希望对你有用。

dsuiofh的博客 860

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

学习必备的50条非常有趣且实用的Python一行代码,值得收藏

前言 学习必备的50条非常有趣且实用的Python一行代码,值得收藏! 让我们愉快地开始吧~编程学习资料免费点击 开发工具 Python版本: 3.6.4 相关模块: 环境搭建 安装Python并添加到环境变量,pip安装需要的相关模块即可。 1、字母异位词 两个单词如果包含相同的字母,次序不同,则称为字母易位词(anagram)。 例如,“silent”和“listen”是字母易位词,而“apple”和“aplee”不是易位词。 fromcollectionsimportCo...

m0_63171455的博客 1万+

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

小白建议收藏,python20条非常实用的代码

Python一直以来被诟病速度慢,影响开发效率,希望这次Guido老爷子能帮python打一场漂亮的翻身仗。 这篇文章不准备介绍Python速度如何,而是给大家带来一些常用且实用的Python代码实例,几乎是开发者必备的知识点。 1、合并两个字典 Python3.5之后,合并字典变得容易起来。我们可以通过**符号解压字典,并将多个字典传入{}中,实现合并。 defMerge(dict1,dict2): res={**dict1,**dict2} return...

m0_58520183的博客 186

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

20个Python人工智能类库!超实用,建议收藏食用!

1、Numpy `NumPy(Numerical Python)`是 `Python`的一个扩展程序库,支持大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库,`Numpy`底层使用`C语言`编写,数组中直接存储对象,而不是存储对象指针,所以其运算效率远高于`纯Python代`码。我们可以在示例中对比下`纯Python`与使用`Numpy库`在计算列表sin值的速度对比:

2301_78217634的博客 3143

学习Python,这29个实用小技巧你如果不知道的话,那亏大了!【纯干货,建议收藏】

前言 先收藏,再点赞,今后好运定不断! 各位优快云上的朋友们大家好,先厚脸皮讨要个三连支持吧!希望这篇文章能帮助到你! 好了!废话不多说,直接上干货: 技巧目录前言1、使用字典来存储选择操作2、一行代码计算任何数的阶乘3、找到列表中出现最频繁的数4、重置递归限制5、原地交换两个数字6、链状比较操作符7、使用三元操作符来进行条件赋值8、检查一个对象的内存使用9、使用slots来减少内存开支10、使用lambda来模仿输出方法11、从两个相关的序列构建一个字典12、一行代码搜索字符串的多个前后缀13、在Pyt

smengo的博客 8860
上一篇: 985研究生连算法都不会,还面试什么大厂!
下一篇: 最新世界大学排名出炉!浙江大学首次跻身全球50强!
菜鸟学Python
博客等级 码龄9年 8040粉丝 571原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值