15个极简Python代码,拿走即用

601 阅读2分钟

参考于公众号:Z先生点记

一、重复元素判定

以下方法可以检查给定列表是否存在重复元素,它会使用 set() 函数来移除所有重复元素。

二、字符元素组成判定

检查两个字符串的组成元素是否一样。

三、内存占用

四、字节占用

![](https://upload-images.jianshu.io/upload_images/7705787-e96b582e7a365f6d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

五、打印 N 次字符串

该代码块不需要循环语句就能打印 N 次字符串

![](https://upload-images.jianshu.io/upload_images/7705787-fe128d813ae3923a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

六、大写第一个字母

以下代码块会使用 title() 方法,从而大写字符串中每一个单词的首字母。

![](https://upload-images.jianshu.io/upload_images/7705787-4cfb21028692bbc5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

七、分块

给定具体的大小,定义一个函数以按照这个大小切割列表。

![](https://upload-images.jianshu.io/upload_images/7705787-d1b84428a81e64d7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

八、压缩

这个方法可以将布尔型的值去掉,例如(False,None,0,“”),它使用 filter() 函数。

![](https://upload-images.jianshu.io/upload_images/7705787-9014f91f4bfec096.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

九、解包

如下代码段可以将打包好的成对列表解开成两组不同的无组。

![](https://upload-images.jianshu.io/upload_images/7705787-a5a81f2aaf98b3a4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

十、链式对比

我们可以在一行代码中使用不同的运算符对比多个不同的元素。

![](https://upload-images.jianshu.io/upload_images/7705787-95bf4721a6db4587.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

十一、逗号连接

下面的代码可以将列表连接成单个字符串,且每一个元素间的分隔方式设置为了逗号

![](https://upload-images.jianshu.io/upload_images/7705787-7468d38f99f3475b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

十二、元音统计

以下方法将统计字符串中的元音 (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) 的个数,它是通过正则表达式做的。

![](https://upload-images.jianshu.io/upload_images/7705787-24e3682bb11e86fd.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

十三、首字母小写

如下方法将令给定字符串的第一个字符统一为小写。

![](https://upload-images.jianshu.io/upload_images/7705787-86fa9fa1e3bd07d3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

十四、展开列表

该方法将通过递归的方式将列表的嵌套展开为单个列表。

![](https://upload-images.jianshu.io/upload_images/7705787-7b24f05b0aa4aa98.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

十五、列表的差

该方法将返回第一个列表的元素,其不在第二个列表内。如果同时要反馈第二个列表独有的元素,还需要加一句 set_b.difference(set_a)。

![](https://upload-images.jianshu.io/upload_images/7705787-30a0fa7b236f955a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)