变量值交换
a, b = 5, 10
a, b = b, a
将列表元素组合成字符串
list1 = ["python", "hello"]
str1 = "".join(list1)
# 注 列表中需要是字符串,如果是int类型报错
字符串拼接的方式
str1 + str2
"hello %s" % "python" # %s占位符
"hello {}".format("python") # format()
str1 = "python"
f"hello{str1}" # f-string
查询列表中频率最高的值
list1 = [1,2,3,4,5,4,3,1,1,1]
# 第一种普通方案
print(max(set(lsit1), key=list1.count))
# 第二种模块方案
from collections import Counter
a = Counter
print(a.most_common(1)) # 1代表取最大的一个,2代表取出最大的两个 格式 列表套元祖
检查两个字符串是不是由相同字母不同顺序组成
from collections import Counter
str1 = "qwer"
str2 = "rewq"
if Counter(str1) == Counter(str2)
print("the same")
else:
print("different")
反转字符串
str1 = "qwer"
print(str1[::-1]) # 切片处理
for i in reversed(str1): # reserved()函数
print(i)
str2 = 12345678
print(int(str(str2)[::-1])) # 数字反转
反转列表
list1 = [1,2,3,4,5]
print(list1[::-1])
字典get方法
dict1 = {1:2,3:4}
print(dict1.get(5, "default value")) # 不存在返回None 或者可以给默认值,不会报错
for-else
for i in set1:
print(i)
else:
print("遍历set1完成")
转换列表为逗号分割符格式
list1 = ["hello", "python"]
print(",".join(list1))
list2 = [1,2,3,4,5]
print(",".join(map(str, list2)))
list3 = [1,"python",2]
print(",".join(map(str, list3)))
# hello,python
# 1,2,3,4,5
# 1,python,2
合并字典
dict1 = {"1":2}
dict2 = {"3":4}
dict1.update(dict2)
print(dict1)
print(dict(dict1.items() | dict2.items()))
移除列表中的重复元素
list1 = [1,2,3,4,4,3,2,1]
print(list(set(list1)))
from collections import OrderedDict
print(OrderedDict.fromkeys(list1).keys()) # <class 'odict_keys'>类型
根据键排序字典
dict1 = {"apple":10,"banana":5}
print(sorted(dict1,key=lambda x:x[1])) # ['banana', 'apple']
from operator import itemgetter
print(sorted(dict1.items(), key=itemgetter(1))) # [('banana', 5), ('apple', 10)]
匿名函数
# 没有名字的函数
# 写法:
# 第一步: 创建一个匿名函数,作用是实现两个数的和。
lambda num1 , num2 : num1 + num2
# 第二步:使用一个变量来去接收这个匿名函数
sum = lambda num1 , num2 : num1 + num2
# 第三步:调用此匿名函数
sum(10 , 20)
copy / deepcopy
copy浅拷贝只拷贝可变类型的第一层,对于不可变类型是引用
deepcopy 深拷贝拷贝可变类型的所有层,对于不可变类型是引用
转置二维数组
list1 = [[1,2],[3,4],[5,6]]
transposed = zip(*list1) # <zip object at 0x0000016E30A693C8>
print(list(transposed)) # [(1, 3, 5), (2, 4, 6)]
列表表达死
list1 = [1,2,3,4,5,6]
new_list = [i * 2 for i in list1 if i % 2 == 0]
print(new_list)