震惊了!每30秒学会一个Python小技巧,Github星数4600+

python 比较list差异 参考:https://blog.youkuaiyun.com/weixin_33736048/article/details/91724635 初始化数据 listA = ['zhangsan', 'lisi', 'wangwu'] listB = ['zhangsan', 'lisi', 'zhaoliu'] 1、取差集 1.1、listA对应listB的差集 set(listA).diff... 阅读详情
很多学习Python的朋友在项目实战中会遇到不少功能实现上的问题,有些问题并不是很难的问题,或者已经有了很好的方法来解决。当然,孰能生巧,当我们代码熟练了,自然就能总结一些好用的技巧,不过对于那些还在刚熟悉Python的同学可能并不会那么轻松。

本次给大家推荐一个学习这些技巧的很好的资源“30-seconds-of-python”,所有技巧方法只要30秒就能get到,完全可以利用业务时间不断积累。下面赶紧来看一下。
https://github.com/30-seconds/30-seconds-of-python
640?wx_fmt=png
1.内容目录
下面是30秒学Python的整个目录,分为几大板块:List、Math、Object、String、Utility,以下是整理的思维脑图。

640?wx_fmt=jpeg


我挑选了10个实用并很有意思的方法分享给大家,其余的感兴趣可以自行学习。



1. List:all_equal

功能实现:检验一个列表中的所有元素是否都一样。

解读:使用[1:] 和 [:-1] 来比较给定列表的所有元素。

def all_equal(lst):
return lst[1:] == lst[:-1]

举例:

all_equal([1, 2, 3, 4, 5, 6]) # False
all_equal([1, 1, 1, 1]) # True



2. List:all_unique

功能实现:如果列表所有值都是唯一的,返回 True,否则 False

解读:在给定列表上使用集合set()去重,比较它和原列表的长度。


def all_unique(lst):
return len(lst) == len(set(lst))

举例:

x = [1,2,3,4,5,6]
y = [1,2,2,3,4,5]
all_unique(x) # True
all_unique(y) # False



3. List:bifurcate

功能实现:将列表值分组。如果在filter的元素是True,那么对应的元素属于第一个组;否则属于第二个组。

解读:使用列表推导式和enumerate()基于filter元素到各组。

def bifurcate(lst, filter):
return [
[x for i,x in enumerate(lst) if filter[i] == True],
[x for i,x in enumerate(lst) if filter[i] == False]
]

举例:

bifurcate(['beep', 'boop', 'foo', 'bar'], [True, True, False, True])

# [ ['beep', 'boop', 'bar'], ['foo'] ]



4. List:difference

功能实现:返回两个iterables间的差异。

解读:创建b的集合,使用a的列表推导式保留不在_b中的元素。

def difference(a, b):
_b = set(b)
return [item for item in a if item not in _b]


举例:


difference([1, 2, 3], [1, 2, 4]) # [3]



5. List:flatten

功能实现:一次性的整合列表。

解读:使用嵌套的列表提取子列表的每个值。

def flatten(lst):
return [x for y in lst for x in y]

举例:

flatten([[1,2,3,4],[5,6,7,8]]) # [1, 2, 3, 4, 5, 6, 7, 8]



6. Math:digitize

功能实现:将一个数分解转换为个位数字。

解读:将n字符化后使用map()函数结合int完成转化

def digitize(n):
return list(map(int, str(n)))


举例:

digitize(123) # [1, 2, 3]



7. List:shuffle

功能实现:将列表元素顺序随机打乱。

解读:使用Fisher-Yates算法重新排序列表元素。

from copy import deepcopy
from random import randint

def shuffle(lst):
temp_lst = deepcopy(lst)
m = len(temp_lst)
while (m):
m -= 1
i = randint(0, m)
temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m]
return temp_lst

举例:

foo = [1,2,3]
shuffle(foo) # [2,3,1] , foo = [1,2,3]



8. Math:clamp_number

功能实现:将数字num钳在由a和b边界值规定的范围中。

解读:如果num落尽范围内,返回num;否则,返回范围内最接近的数字。

def clamp_number(num,a,b):
return max(min(num, max(a,b)),min(a,b))

举例:

clamp_number(2, 3, 5) # 3
clamp_number(1, -1, -5) # -1


9. String:byte_size

功能实现:返回字符串的字节数。

解读:使用string.encode('utf-8')解码给定字符串,返回长度。

def byte_size(string):
return len(string.encode('utf-8'))

举例:

byte_size('?') # 4
byte_size('Hello World') # 11



10. Math:gcd

功能实现:计算几个数的最大公因数。

解读:使用reduce()和math.gcd在给定列表上实现。

from functools import reduce
import math

def gcd(numbers):
return reduce(math.gcd, numbers)


举例:

gcd([8,36,28]) # 4


以上就是30秒学python的各种小技巧。怎么样,对于一些常见操作是不是有了一些新的启发,除此之外,还有很多其它技巧可以慢慢学习,希望对各位读者有所帮助。

https://github.com/30-seconds/30-seconds-of-python


近期热门:



千人学习群:

喜欢文章,点个在看

我的个人网站构建与GitHub Pages使用经验分享 本文还有配套的精品资源,点击获取 简介:本文介绍了个人网站的建设过程,特别是在GitHub Pages上部署Jekyll博客的经历。作者详细讲解了如何使用Jekyll静态站点生成器,选择合适的响应式设计主题,以及利用JavaScript和Markdown技术增强网站的动态功能和内容管理。通过GitHub仓库管理,实现了网站内容的版本控制和部署,展示了个人技能和开源工具如何相... 阅读详情

相关推荐

手把手教你用ZEMAX复现贝塞尔光束:从Thorlabs锥透镜到Edmund透镜的完整光路搭建

本文详细介绍了如何在ZEMAX光学设计软件中复现贝塞尔光束,从Thorlabs锥透镜到Edmund透镜的完整光路搭建过程。通过逐步指导,帮助研究人员和工程师掌握光学设计技巧,实现无衍射特性的贝塞尔光束生成,适用于激光加工和生物成像等领域。

weixin_33737774的博客 181

2023年最新 Github Pages 使用手册

GitHub Pages 是一项静态站点托管服务,它直接从 GitHub 上的仓库获取 HTML、CSS 和 JavaScript 文件,(可选)通过构建过程运行文件,然后发布网站。可以在GitHub Pages 示例集合中看到 GitHub Pages 站点的示例。可以有两个方式:仓库内创建 404.md,但是开头需要配置 yml 格式------...仓库内创建 404.html

SiShen654的博客 1万+

Windows 10/11下Drive Composer Pro 2.9.0完整安装与连接ACS880变频器实战教程

本文详细介绍了在Windows 10/11系统上安装Drive Composer Pro 2.9.0并连接ACS880变频器的完整教程。从系统环境准备、软件安装到许可证配置,再到USB、蓝牙和以太网三种连接方式的实战操作,帮助工业自动化工程师快速掌握ABB变频器的调试技巧。

weixin_32956805的博客 528

保姆级教程:从零构建GitHub Pages静态网站

超详细讲解从零构建Github Pages静态网站

阿甘兄 6万+

从单应矩阵到实际距离:Apriltag测距完整实现指南

本文提供了基于Apriltag实现高精度视觉测距与姿态估计的完整指南。详细阐述了从相机标定、单应矩阵分解到欧拉角与距离计算的完整流程,并深入探讨了四个解的歧义选择、工程实践中的滤波优化与多Tag融合等关键问题,旨在帮助开发者在机器人、AR等应用中实现稳定可靠的距离检测与姿态估计。

n7o8p的博客 559

教你搞懂RT-Thread的移植和配置ENV工具环境

RT-Thread的移植和配置ENV工具环境

Troubadour~的博客 8263

github pages 用法详解

详细介绍 github pages 的使用方法,包括基础用法和通过 actions 自动发布

lancemao的博客 1万+

huggingface 镜像站推荐

在做 Ai 应用开发或者学习的时候,我们经常需要下载各种模型,而 huggingface 的模型下载速度很慢或者根本就连不上,这里推荐一个 huggingface 的镜像站,速度很快,可以大大提高我们的效率。

t951984189的博客 1万+

如何使用Github Page搭建个人网站【踩坑实录&多图预警】

使用GIthub Page 搭建个人网站的全过程记录

WHYbeHERE的博客 1万+

STM32 IIC电量计LTC2944

LTC2944是一款电池电量计,设计用于端电压为3.6V至60V的多节电池。它测量电池充电和放电、电池电压、电流和自身温度。精密模拟库仑计数器通过电池正极端子与负载或充电器之间的检测电阻器对电流进行积分。电池电压、电池电流和硅温度由内部ADC测量。

baidu_34971492的博客 3161

华为OD机试真题 新系统 2026-09-26 Java&Go&C【数据中心最佳维护时间窗】

数据中心使用一个整数数组 scores,记录 N 小时内每小时的服务器得分(可正可负)。0 表示服务器故障(无效小时)。

MISAYAONE的博客 100

利用github搭建个人博客(超级简单,一看包会)

利用github Pages搭建个人博客

前端大波的博客 4686

基于YOLOv8的城市违建识别系统:从数据集构建到UI界面实现

YOLOv8是Ultralytics公司于2023年推出的最新一代YOLO(You Only Look Once)系列目标检测算法。更高效的骨干网络设计改进的锚框机制更精确的损失函数支持分类、检测、分割等多任务YOLOv8特别适合像违建识别这样的实时检测任务,能够在保持高精度的同时实现快速推理。

YOLO 675

quartz 每30秒执行一次_震惊了!每30秒学会一个Python小技巧,Github星数4600+

文章来源于Python数据科学 ,作者wLsq很多学习Python的朋友在项目实战中会遇到不少功能实现上的问题,有些问题并不是很难的问题,或者已经有了很好的方法来解决。当然,孰能生巧,当我们代码熟练了,自然就能总结一些好用的技巧,不过对于那些还在刚熟悉Python的同学可能并不会那么轻松。本次给大家推荐一个学习这些技巧的很好的资源“30-seconds-of-python”,所有技巧方法只要30秒...

weixin_42347426的博客 240

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

深度学习工具包 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")

python list突破上限武器_震惊了!每30秒学会一个Python小技巧,Github星数4600+

原标题:震惊了!每30秒学会一个Python小技巧,Github星数4600+导读:很多学习Python的朋友在项目实战中会遇到不少功能实现上的问题,有些问题并不是很难的问题,或者已经有了很好的方法来解决。当然,孰能生巧,当我们代码熟练了,自然就能总结一些好用的技巧,不过对于那些还在刚熟悉Python的同学可能并不会那么轻松。本次给大家推荐一个学习这些技巧的很好的资源“30-seconds-of-...

weixin_39737224的博客 103

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

python打乱list_震惊了!每30秒学会一个Python小技巧,Github星数4600+

关注上方“数据挖掘工程师”,选择星标,关键时间,第一时间送达!作者:xiaoyu,数据爱好者Python数据科学出品很多学习Python的朋友在项目实战中会遇到不少功能实现上的问题,有些问题并不是很难的问题,或者已经有了很好的方法来解决。当然,孰能生巧,当我们代码熟练了,自然就能总结一些好用的技巧,不过对于那些还在刚熟悉Python的同学可能并不会那么轻松。本次给大家推荐一个学习这些技巧...

weixin_35304361的博客 142

创建Github Pages 仓库

在 GitHub 上创建一个 GitHub Pages 仓库是相对简单的。GitHub Pages 允许您将您的代码仓库发布为一个静态网站。如果您使用的是其他分支,确保在 “Settings” -> “Pages” 中正确设置了分支。在您的仓库中,您可以添加一个简单的 HTML 文件,或者将整个网站的代码上传到仓库。如果您使用了分支,确保您的静态网站文件位于该分支的根目录。代码编写(简易编写一个Hello, World!请注意,GitHub Pages 默认使用。

AiENG_07的博客 3597

0基础学前端 day6 -- 搭建github pages静态网址

标题:如何通过 GitHub Pages 创建一个静态网站GitHub Pages 是 GitHub 提供的一项免费服务,允许用户从 GitHub 仓库中托管静态网站。对于开发者和非开发者来说,这都是一个极其便利的工具,用于创建和发布个人博客、项目文档或作品集。GitHub Pages 是基于 GitHub 仓库创建的静态网站托管服务。用户可以把 Markdown 或 HTML 文档转化为网站来展示,并拥有一个免费的 github.io 域名。这些网站通常托管在 GitHub 的服务器上,任何人都可以通过浏

无限大的博客 2474

github pages 用法详解 发布自己的网站

这里的分支选择、目录选择都是很巧妙的设计。主分支一般是放代码的,不会放 index.html 这样的网页内容。所以一个方案就是通过目录,把网页放到 docs 目录下。pages 发布的时候,会花费点时间,请耐心等待约 1-5 分钟。用任意编辑器写好(或者生成)标准的网页内容,push 到 myrepo 即可。和大部分 web 服务一样,pages 会到指定目录里面寻找 index.html 作为网页入口。

李十三的博客 3728

全网最详细的GitHub Pages上部署项目

无需购买服务器或进行复杂的配置,只需将静态文件推送到特定的分支,GitHub Pages就会自动为你托管网站。如果你的项目需要构建(例如使用 React、Vue 或 Angular),请确保已经构建好,并且所有构建输出文件在一个目录中(例如。如果你的项目是一个单页应用(SPA),你可能需要使用打包工具(如Webpack、Vite等)来构建项目。通过这些步骤,你可以轻松地在 GitHub Pages 上部署你的静态网站或项目。GitHub Pages 会自动生成一个 URL,你可以在上面访问你的项目。

共同进步 5366
上一篇: 麦当劳叔叔用 AI 面试服务员,合格就录用
下一篇: 物联网激荡20年
菜鸟学Python
博客等级 码龄9年 8062粉丝 571原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值