最全Python一行代码片段,可直接使用

Write less to achieve more.


追求极简是优秀程序员的特质之一,简洁的代码,不仅看起来更专业,可读性更强,而且减少了出错的几率。

本文盘点一些Python中常用的一行(不限于一行)代码,可直接用在日常编码实践中。

欢迎补充交流!


1. If-Else 三元操作符(ternary operator)

 #<on True> if <Condition> else <on False>
print("Yay") if isReady else print("Nope")

2. 交换(swap)两个变量值

 a, b = b, a 

3. 匿名函数(Lambda)过滤列表

 >>> numbers = [1, 2, 3, 4, 5, 6]
>>> list(filter(lambda x : x % 2 == 0 , numbers))

4. 模拟丢硬币(Simulate Coin Toss)

使用random模块的choice方法,随机挑选一个列表中的元素

 >>> import random
>>> random.choice(['Head',"Tail"])
Head

5. 读取文件内容到一个列表

 >>> data = [line.strip() for line in open("file.txt")] 

6. 最简洁的斐波那契数列实现

 fib = lambda x: x if x <= 1 else fib(x - 1) + fib(x - 2) 

7. 字符串转换成字节

 "convert string".encode()
# b'convert string'

8. 反转(Reverse)一个列表

 numbers[::-1] 

9. 列表推导式(List comprehension)

 even_list = [number for number in [1, 2, 3, 4] if number % 2 == 0]
# [2, 4]

10. print语句将字符串写入文件

挺方便,类似于linux中的

echo string &gt; file

 print("Hello, World!", file=open('file.txt', 'w')) 

11. 合并两个字典

 dict1.update(dict2) 

12. 按字典中的value值进行排序

 dict = {'a':24, 'g': 52, 'i':12, 'k':33}
#reverse决定顺序还是倒序
sorted(dict.items(), key = lambda x:x[1], reverse=True)

标签: python

添加新评论