多变量赋值
a, b, c = 2, 3.3, 'python'
print(a, b, c) #结果: 2 3.3 python
a, b, *c = [1, 2,3, 4, 5]
print(a, b, c) #结果: 1 2 [3, 4, 5]
删除列表中的重复项
使用set来消除重复项。set是一种无序集合,其中每个元素都是唯一的。这意味着如果我们将列表变成一个集合,就可以快速删除重复项,。然后我们只需要将集合再次转换为列表即可。
numbers = [1, 1, 1, 2, 2, 3, 4, 5, 5]
print(list(set(numbers))) #结果:[1, 2, 3, 4, 5]
从列表中过滤值
使用 filter() 函数。语法:filter(function, iterable)
。在过滤器函数中添加一个lambda函数,效果更好!
案例:过滤出列表[10, 15, 17, 34]中的偶数。
my_list = [10, 15, 17, 34]
print(list(filter(lambda x: x%2 ==0, my_list))) #结果:[10, 34]
一行if…else语句
要在一行中编写if…else语句,我们将使用三元运算符。三元的语法是[on true] if [expression] else [on false]
。
# 单条件
score = 97
if score > 90: print("Excellent") # Excellent
# 双条件
print("Excellent") if score > 90 else print("Great")
# 多条件
print("Excellent") if score > 90 else print("Great") if score > 80 else print("Good")
一行for循环
for循环是一个多行语句,但是在Python中,我们可以使用列表推导式方法在一行中编写for循环。
案例:过滤出列表[0, 5, 12, 34]中大于10的值。
mylist = [0, 5, 12, 34]
# 正常解法
result = []
for i in mylist:
if i > 10:
result.append(i)
print(result) # [12, 34]
# 一行代码
result = [i for i in mylist if i > 10]
print(result) # [12, 34]
一行while循环
# 单语句
while True: print("Done") # 死循环
# 多语句
i = 0
while i < 5: print(i); i+=1 # 0 1 2 3 4
一行合并字典
d1 = {'A': 1, 'B': 2}
d2 = {'C': 3, 'D': 4}
# 方法1:
d1.update(d2)
print(d1) # {'A': 1, 'B': 2, 'C': 3, 'D': 4}
# 方法2:使用解包运算符 **
d3 = {**d1, **d2}
print(d3) # {'A': 1, 'B': 2, 'C': 3, 'D': 4}
一行函数
# 方法1:使用与三元运算符或单行循环方法相同的函数定义
def fun(x): return True if x % 2 == 0 else False
print(fun(3)) # False
# 方法2:使用lambda定义函数
fun = lambda x: x % 2 == 0
print(fun(6)) # True