很多学习Python的朋友在项目实战中会遇到不少功能实现上的问题,有些问题并不是很难的问题,或者已经有了很好的方法来解决。当然,孰能生巧,当我们代码熟练了,自然就能总结一些好用的技巧,不过对于那些还在刚熟悉Python的同学可能并不会那么轻松。
本次给大家推荐一个学习这些技巧的很好的资源 “30-seconds-of-python” , 所有技巧方法只要30秒就能get到,完全可以利用业务时间不断积累。下面赶紧来看一下。

1.内容目录
【ps:更多精彩案例视频,基础,进阶,爬虫,数据分析等学习资料加q群778463939免费获取】
下面是30秒学Python的整个目录,分为几大板块:List、Math、Object、String、Utility,以下是整理的思维脑图。

我挑选了10个实用并很有意思的方法分享给大家,其余的感兴趣可以自行学习。
1. List: all_equal
功能实现: 检验一个列表中的所有元素是否都一样。
解读: 使用 [1:] 和 [:-1] 来比较给定列表的所有元素。

举例:

2. List: all_unique
功能实现: 如果列表所有值都是唯一的,返回 True ,否则 False
解读: 在给定列表上使用集合 set() 去重,比较它和原列表的长度。

举例:

3. List:bifurcate
功能实现: 将列表值分组。如果在 filter 的元素是 True ,那么对应的元素属于第一个组;否则属于第二个组。
解读:使用列表推导式和 enumerate() 基于 filter 元素到各组。

举例:
bifurcate([ ' beep ' , ' boop ' , ' foo ' , ' bar ' ], [ True , True , False , True ])
# [ ['beep', 'boop', 'bar'], ['foo'] ]
4. List: difference
功能实现: 返回两个iterables间的差异。
解读: 创建b的集合,使用a的列表推导式保留不在_b中的元素。

举例:

5. List: flatten
功能实现: 一次性的整合列表。
解读: 使用嵌套的列表提取子列表的每个值。

举例:

6. Math:digitize
功能实现: 将一个数分解转换为个位数字。
解读:将n字符化后使用 map() 函数结合 int 完成转化

举例:

7. List: shuffle
功能实现: 将列表元素顺序随机打乱。
解读:使用Fisher-Yates算法重新排序列表元素。

举例:

8. Math: clamp_number
功能实现: 将数字 num 钳在由a和b边界值规定的范围中。
解读: 如果 num 落尽范围内,返回 num ;否则,返回范围内最接近的数字。

举例:

9. String: byte_size
功能实现: 返回字符串的字节数。
解读:使用 string.encode('utf-8') 解码给定字符串,返回长度。

举例:

10. Math: gcd
功能实现: 计算几个数的最大公因数。
解读: 使用 reduce() 和 math.gcd 在给定列表上实现。

举例:

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