list1.append(x)
: 将x添加到列表末尾
list1.sort()
: 对列表元素排序
list1.reverse()
: 将列表元素逆序
list1.index(x)
: 返回第一次出现元素x的索引值
list1.insert(x)
: 在位置i处插入新元素x
list1.count(x)
: 返回元素x在列表中的数量
list1.remove(x)
: 删除列表中第一次出现的元素x
list1.pop(i)
: 取出列表中i位置上的元素,并将其删除
# 演示重要的内容
list1 = [1,2,5,4,3]
list1.sort() # 默认为升序且直接改变原列表顺序,等价于 list1.sort(reverse=False)
print('默认升序:',list1)
list1.sort(reverse=True)
print('reverse=True为降序:',list1)
默认升序: [1, 2, 3, 4, 5]
reverse=True为降序: [5, 4, 3, 2, 1]
列表与字典相关技巧:
# python 根据 key,value 排序字典
d = {'d': 4, 'a': 1, 'b': 2, 'c':3}
# dict sort by key and reverse
print(dict(sorted(d.items()))) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
print(dict(sorted(d.items(),reverse=True))) # {'d': 4, 'c': 3, 'b': 2, 'a': 1}
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
{'d': 4, 'c': 3, 'b': 2, 'a': 1}
# 排序嵌套 list
l = [('a', 1), ('c', 2), ('b',3)]
print(sorted(l, key=lambda p:p[0])) # 根据第1个值排序,[('a', 1), ('b', 3), ('c', 2)]
print(sorted(l, key=lambda p:p[1])) # 根据第2个值排序,[('a', 1), ('c', 2), ('b', 3)]
[('a', 1), ('b', 3), ('c', 2)]
[('a', 1), ('c', 2), ('b', 3)]
# 同时获取最大值的下标和值
lis = [1,2,5,4,3]
max_index,max_value = max(enumerate(lis),key=lambda iv:iv[1])
print('最大值的下标:',max_index,'、','最大值为:',max_value)
最大值的下标: 2 、 最大值为: 5
# 获取字典对应的最大值对应的 key,value
mydict = {'A':4,'B':10,'C':0,'D':87}
max_key, max_value = max(mydict.items(), key=lambda k: k[1])
print('最大值的key:',max_key,'、','最大值为:',max_value)
最大值的key: D 、 最大值为: 87
abs(x)
: 取x的绝对值
pow()
: pow(3,4)求3的四次方
min(list1)
: 取列表中的最小值
max(list1)
: 取列表中的最大值
sum(list1)
: 取列表中的和
zip()
: 创建一个聚合了来自每个可迭代对象中的元素的迭代器。
x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
print(list(zipped)) # [(1, 4), (2, 5), (3, 6)]
# zip() 与 * 运算符相结合可以用来拆解一个列表:
x2, y2 = zip(*zip(x, y))
print(x == list(x2) and y == list(y2))
ord()
: 将ASCLL码转换为数字。ord('a')返回91
chr()
: 将数字转换为ASCLL码。chr(97) 返回字符串 'a'
str1.swapcase()
: 翻转 str1 中的大小写
list(str1)
: 将字符串转化为列表
''.join(str1)
: 将字符串列表,拼成字符串
srt1.split()
:将字符串按一定符号分割,分割后成列表
srt1.isdigit()
: 检测字符串是否由十进制数 0--9
组成
str1.isnumeric()
: 检测字符串是否只由数字组成
srt1.isxdigit()
: 检测字符串是否由十六进制数 0--9,a—f,或A--F
组成
srt1.isalnum()
: 检测字符串是否由字母数字符号 0--9,a--Z,或A--Z
组成
srt1.isalpha()
: 检测字符串是否由字母a--Z或A--Z
组成
srt1.islower()
: 检测字符串是否否由小写字母 a--Z
组成
srt1.isupper()
: 检测字符串是由 大写字母 A--Z
组成
strip() / lstrip() / rstrip()
: 用于移除字符串头尾 / 开头 / 结尾指定的字符(默认为空格)
https://blog.csdn.net/qq_41196691/article/details/109597863
https://blog.csdn.net/weixin_41259130/article/details/79690172
https://docs.python.org/zh-cn/3.8/library/functions.html