常用Python简洁代码片段

2022/2/7 1:15:41

本文主要是介绍常用Python简洁代码片段,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Write less to achieve more.
用尽可能的少的代码实现复杂功能。

本文介绍一些实用的代码简洁小技巧,让你的代码看起来更专业,可读性更强。

1. 单行 If-Else

isReady = False

# A regular if-else
if isReady:
    print("Yay")
else:
    print("Nope")
    
# A neat little shorthand
print("Yay") if isReady else print("Nope")

2. 交换(swap)两个变量值,不使用临时变量

a = 1
b = 2

a, b = b, a

# Now a = 2 and b = 1

3. 链式比较(Chain Comparisons)

# regular one
x > 0 and x < 200

# neat
0 < x < 200

4. 匿名函数(Lambda Expressions)

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

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

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

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


这篇关于常用Python简洁代码片段的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程