前言
本文紧随上文,继续给大家介绍python中可以提高我们代码可读性的一些技巧。
一、获得两个集合的并集
初级
将两个集合合并,且将元素添加到一个新集合中
set_a = {1, 2, 4, 8}
set_b = {3, 8, 7, 1, 9}
union_set = set()
for i in set_a:
union_set.add(i)
for i in set_b:
union_set.add(i)
print(union_set)
# {1, 2, 3, 4, 7, 8, 9}
进阶
python为两个集合的并集提供了**union()**方法
set_a = {1, 2, 4, 8}
set_b = {3, 8, 7, 1, 9}
union_set = set_a.union(set_b)
print(union_set)
# {1, 2, 3, 4, 7, 8, 9}
二、更改列表中所有元素的数据类型
任务:给定一个表示整数的字符串列表,更改数据类型将他们转换为整数的列表
初级
循环遍历列表并对单个元素进行类型转换
input_list = ["7", "2", "13", "15", "0"]
output_list = []
for idx, i in enumerate(input_list):
output_list.append(int(input_list[idx]))
print(output_list)
# [7, 2, 13, 15, 0]
进阶
使用Python的map函数,如下所示
input_list = ["7", "2", "13", "15", "0"]
output_list = list(map(int, input_list))
print(output_list)
# [7, 2, 13, 15, 0]
作为其第一个参数,map()方法接受一个函数 int,第二个参数是一个可迭代对象 input_list
三、交换变量
给定两个变量,目标是将第一个变量的值传递给第二个变量,将第二个变量的值传递给第一个变量
初级
大多数的时候,我们都会新定义一个新变量temp
a = "123"
b = "abc"
temp = a
a = b
b = temp
print(a, b)
# abc 123
进阶
而Python 允许在单个语句中进行多次赋值,从而消除对临时变量的需要,就是解包啦,之前教程都有说过
a = "123"
b = "abc"
a, b = b, a
print(a, b)
# abc 123
四、使用嵌套循环生成两个列表的所有组合
给定两个列表(a的长度为 n,b的长度为m),生成所有n*m结构
初级
使用两个嵌套循环for,将所有组合添加到列表中
list1 = ["A", "B", "C"]
list2 = [1, 2]
combinations = []
for i in list1:
for j in list2:
combinations.append([i, j])
print(combinations)
# [['A', 1], ['A', 2], ['B', 1], ['B', 2], ['C', 1], ['C', 2]]
进阶
可以使用tertools库中的product()的方法,如下所示
from itertools import product
list1 = ["A", "B", "C"]
list2 = [1, 2]
combinations = list(product(list1, list2))
print(combinations)
# [('A', 1), ('A', 2), ('B', 1), ('B', 2), ('C', 1), ('C', 2)]
总结
整理不易,你的点赞和关注就是对我最大的支持。有哪里不懂得也可以在评论区指出来哦