Python 列表推导式使用有哪些注意事项?(干货建议收藏)

Python列表生成式的用法 在上面的示例中,我们通过添加条件语句(num % 2 == 0)来筛选出numbers列表中的偶数,然后创建了一个新的even_numbers列表。外层的列表生成式用于生成每一行,内层的列表生成式用于生成每一行中的元素。在上面的示例中,我们通过遍历numbers列表中的每个元素,并将其乘以2,创建了一个新的doubled_numbers列表。在上面的示例中,我们使用了字符串的upper()方法将每个字符串转换为大写,并创建了一个新的upper_fruits列表。示例4:嵌套的列表生成式。 阅读详情

Python 列表推导式并不是给初学者用的,因为它非常反直觉,甚至对于有其他编程语言背景的人也是如此。

我们接触到 List 的使用时,学习的内容都是零散的。所以我们缺少一个关于如何在各种各样的场景下使用 List 的知识体系。

本文提供了一些 List 的使用指南,尽可能涵盖各个方面。希望本文可以成为你的一站式实用手册。

如果大家在学习中遇到困难,想找一个python学习交流环境,可以加入我们的python裙,裙号930900780,可领取python学习资料,会节约很多时间,减少很多遇到的难题。

使用建议

1.建议使用迭代的方式

使用 List 最基本的方式是以一个可迭代对象为基础,创建一个 List 对象,这个可迭代对象可以是任意可以迭代元素的Python对象。使用方法如下。

[expression for item in iterable]
复制代码

下面这段代码展示了一个使用列表相关技术创建 List 对象的例子。在这个例子中,我们定义了一个 Integer 列表,并基于这个对象创建了保存每个数字的平方数和立方数的 List 对象。

>>> # 创建一个 Integer 列表
>>> integers = [1, 2, 3, 4, 5, 6]
>>> # 创建平方数和立方数列表
>>> powers = [(x*x, pow(x, 3)) for x in integers]
>>> print(powers)
[(1, 1), (4, 8), (9, 27), (16, 64), (25, 125), (36, 216)]

复制代码

上面的例子把 List 对象当作迭代器使用。我们应该知道,许多类型的对象也是可迭代的,比如 List、Set、Dictionary 和 String 等等。其他数据类型,像 range、map、filter,以及 pandas 包中的 Series、DataFrame,都是可迭代的。下面的代码演示了某些对象的使用方法。

>>> # 使用 range 对象
>>> integer_range = range(5)
>>> [x*x for x in integer_range]
[0, 1, 4, 9, 16]
>>> # 使用 Series 对象 
>>> import pandas as pd
>>> pd_series = pd.Series(range(5))
>>> print(pd_series)
0   
Codex CLI 接入智谱 GLM-5.1 完整教程 Codex CLI 是 OpenAI 推出的命令行 AI 编程工具,支持自主读取文件、执行命令、编写代码等操作,是目前最火的终端 AI 编程工具之一。通过 CLIProxyAPI 代理,我们成功将 Codex CLI 与智谱 GLM-5.1 模型对接,核心在于解决 Responses API 与 Chat Completions API 的协议转换问题。✅成熟稳定:CLIProxyAPI 社区活跃(4.7k fork),持续维护✅完整兼容:支持流式/非流式、function calling✅低成本。 阅读详情

相关推荐

双极性步进电机驱动技术:从H桥电路到精准控制

本文深入解析了双极性步进电机驱动技术的核心,从H桥电路的基础原理讲起,阐述了其作为实现电机正反转和精准控制的关键。文章详细介绍了H桥的工作模式、防共态导通设计,并对比了L298N、DRV8825及TMC2209等主流集成驱动芯片的选型。进一步探讨了通过微步进与电流矢量控制实现平滑、静音运行的高级技术,并提供了基于STM32的实战代码与避坑指南,帮助开发者从理论到实践全面掌握精准运动控制。

tea88的博客 603

Prometheus-2.53.1安装

Prometheus+Grafana安装

qlj062127的博客 1790

深入解析磁盘性能测试:vdbench与fio的实战对比

本文深入对比了磁盘性能测试两大工具vdbench与fio的核心定位与实战应用。vdbench擅长多客户端、可编排的存储系统集成测试,而fio则以灵活的单机深度定制见长,是测试硬件极限和模拟特定应用IO模型的利器。文章通过安装指南、参数解析和典型场景对比,帮助读者根据需求选择合适工具,精准评估磁盘性能。

weixin_29300931的博客 336

NVIDIA DGX Spark 深度应用解析:从大模型训练到边缘推理的完整实践指南

内存管理:充分利用统一内存架构,避免不必要的数据传输批处理大小:根据模型大小调整批处理大小以优化内存使用精度选择:在精度损失可接受范围内使用较低精度计算流水线优化:重叠计算和数据传输操作DGX Spark作为一个专门的AI计算平台,在大模型开发的各个阶段都能发挥重要作用。从数据预处理到模型训练,从微调到推理部署,其统一内存架构和强大的计算能力为AI开发者提供了前所未有的本地开发体验。需要注意的是,虽然DGX Spark性能强大,但合理的算法设计和系统优化仍然是获得最佳性能的关键。

time_days的博客 2877

MATLAB之把多个小cell拼成一个数组

问题描述 现有一个cell向量 L (90000,1),每个元素都是由一个(100X9)的double数组组成的.如图. 其中, 每个cell元素都是一个单独的数据, 我们要把它转换成(90000, 19, 100)的三维数组. cell2mat, 但是所有的数据会堆叠起来 L2=cell2mat(L); % (90000, 19) reshape, 变成三维数组 reshape的原理是从上到下, 从左往右拆开重组. 目前只有19这一维数据与要求一致, 那就以这个为突破口. L2=L2'; %

落日之城 9256

<PLC><socket><汇川>汇川PLC使用socket与其他控制器(如上位机)通讯模板程序示例

以上介绍了汇川PLC通用socket通讯的示例,事实上,汇川的官方手册也有使用示例,可以直接仿照使用,也可以加以修改。

用沸腾的热血,支付我们的人生吧! 3258

Unity 工具 之 ZXing QRCode 二维码的生成和识别(可设置生成不同颜色的/带图标的二维码)

Unity 基础 之 ZXing QRCode 二维码的生成和识别(可设置生成不同颜色的/带图标的二维码) 目录 Unity 基础 之 ZXing QRCode 二维码的生成和识别(可设置生成不同颜色的/带图标的二维码) 一、简单介绍 二、实现原理 三、注意实现 四、效果预览 五、ZXing.net ( zxing.unity.dll ) 插件下载 六、实现步骤 七、关键代码 一、简单介绍 Unity 开发中,自己整理的一些游戏开发可能用到的功能,整理归档,方便游...

仙魁XAN 9829

【无人机路径规划】基于强化学习实现多无人机路径规划

【无人机路径规划】基于强化学习实现多无人机路径规划

k8291121的博客 1662

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

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

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

上一篇: 零基础小白Python入门必看:最详细之数据类型讲解
下一篇: 大佬用python写了个豆瓣短评爬虫,有你喜欢的电视试试吗
python小丸子
博客等级 码龄6年 30粉丝 24原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址