1. 按字典 value
值排序
- 要点:对于给定字典,使用
sorted()
函数结合items()
方法,依据value
进行排序,也可以定义一个通用函数,支持按value
升序或降序排序。 - 示例:
python
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# 对字典 d 按值排序,lambda 函数指定排序依据为元素的第二个值(即 value)
sorted_d = dict(sorted(d.items(), key=lambda item: item[1]))
print(sorted_d)
#通用函数方式
def sort_dict_by_value(d, reverse=False):
return dict(sorted(d.items(), key=lambda item: item[1], reverse=reverse))
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
print(sort_dict_by_value(d))
print(sort_dict_by_value(d, reverse=True))
2. 字典推导式的用法和作用
- 要点:字典推导式是简洁创建字典的方式,类似列表推导式,可以结合条件判断,只将满足条件的元素纳入字典。
- 示例:
python
numbers = [1, 2, 3, 4]
# 通过字典推导式,将列表元素作为键,其平方作为值创建字典
squared_dict = {num: num**2 for num in numbers}
print(squared_dict)
#只将满足条件的元素纳入字典
numbers = [1, 2, 3, 4, 5]
# 只将偶数的平方纳入字典
squared_dict = {num: num**2 for num in numbers if num % 2 == 0}
print(squared_dict)
3. 字符串转字典
- 要点:将特定格式字符串按规则分割处理,转换为字典,如果字符串格式比较复杂,如包含引号,可以增加处理逻辑。
- 示例:
python
s = "a:1 |a1:2|a2:3|a3:4"
result = {}
# 去除字符串中的空格并按 | 分割成键值对列表
pairs = s.replace(" ", "").split("|")
for pair in pairs:
# 将每个键值对按 : 分割
key, value = pair.split(":")
result[key] = int(value)
print(result)
# 复杂格式处理
s = ' "a":1 | "a1":2 | "a2":3 | "a3":4 '
result = {}
pairs = s.replace(" ", "").replace('"', "").split("|")
for pair in pairs:
key, value = pair.split(":")
result[key] = int(value)
print(result)
4. 按列表元素 age
排序
- 要点:对包含字典的列表,按字典中的
age
键值从大到小排序,也可以定义一个更灵活的排序函数,支持按不同键排序。 - 示例:
python
alist = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 20}, {'name': 'Charlie', 'age': 30}]
# 使用 sorted 函数,通过 lambda 函数指定按 age 排序,reverse=True 表示降序
sorted_alist = sorted(alist, key=lambda x: x['age'], reverse=True)
print(sorted_alist)
# 定义排序函数,支持按不同键排序
def sort_list_of_dicts(lst, key, reverse=False):
return sorted(lst, key=lambda x: x[key], reverse=reverse)
alist = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 20}, {'name': 'Charlie', 'age': 30}]
print(sort_list_of_dicts(alist, 'age', reverse=True))
5. 写出列表切片的结果
- 要点:如果列表切片索引超出范围时,会返回空列表。
- 示例:
python
my_list = ['a', 'b', 'c', 'd', 'e']
# 切片索引 11 超出列表长度,返回空列表
print(my_list[11:])
6. 列表生成式产生等差数列
- 要点:使用列表生成式创建公差为 7 的等差数列,也可以将其封装成函数,方便生成不同首项和公差的等差数列
- 示例:
python
first_term = 3 # 等差数列首项
num_terms = 10 # 等差数列项数
# 通过列表生成式生成公差为 7 的等差数列
sequence = [first_term + i * 7 for i in range(num_terms)]
print(sequence)
# 函数方式
def arithmetic_sequence(first_term, common_difference, num_terms):
return [first_term + i * common_difference for i in range(num_terms)]
print(arithmetic_sequence(3, 7, 10))
7. 找出两列表相同与不同元素
- 要点:利用集合的交集和对称差集操作,找出两列表相同和不同元素,也可以处理多个列表,找出所有列表的公共元素和不同元素
- 示例:
python
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
# 将列表转换为集合
set1 = set(list1)
set2 = set(list2)
# 求交集得到相同元素
common_elements = list(set1.intersection(set2))
# 求对称差集得到不同元素
different_elements = list(set1.symmetric_difference(set2))
print("相同的元素:", common_elements)
print("不同的元素:", different_elements)
# 多列表方式
lists = [[1, 2, 3, 4, 5], [4, 5, 6, 7, 8], [5, 6, 7, 8, 9]]
sets = [set(lst) for lst in lists]
# 求所有集合的交集
common = list(set.intersection(*sets))
# 先合并所有集合,再求与交集的差集
all_elements = set.union(*sets)
different = list(all_elements - set(common))
print("相同的元素:", common)
print("不同的元素:", different)
8. 删除列表重复元素
- 要点:使用集合去除列表重复元素,再转换回列表,如果需要保留列表元素的原有顺序,可以使用
dict.fromkeys()
方法。 - 示例:
python
my_list = [1, 2, 2, 3, 4, 4, 5]
# 利用集合的唯一性去除重复元素
unique_list = list(set(my_list))
print(unique_list)
# 去重并且保留原来的顺序
my_list = [1, 2, 2, 3, 4, 4, 5]
unique_list = list(dict.fromkeys(my_list))
print(unique_list)
9. 新式类和经典类有什么区别
- 要点:新式类和经典类在继承顺序、基类、属性查找和
__slots__
属性支持上存在差异。Python 3 只有新式类,Python 2 需显式继承object
类创建新式类。 - 示例:
python
# Python 2 代码示例,Python 3 只有新式类
# 经典类
class A:
def method(self):
print("A's method")
class B(A):
pass
class C(A):
def method(self):
print("C's method")
class D(B, C):
pass
d = D()
d.method() # 经典类采用深度优先,输出 A's method
# 新式类
class A_new(object):
def method(self):
print("A_new's method")
class B_new(A_new):
pass
class C_new(A_new):
def method(self):
print("C_new's method")
class D_new(B_new, C_new):
pass
d_new = D_new()
d_new.method() # 新式类采用 C3 线性化,输出 C_new's method