第12天:Python 编程
发布: (2025年12月2日 GMT+8 21:11)
4 min read
原文: Dev.to
Source: Dev.to
第1部分:列表 – 高级概念
列表推导式
- 带条件
嵌套列表推导式
列表切片
重要的列表方法
示例:
# Example of using list methods
my_list = [1, 2, 3, 4, 5]
my_list.append(6) # Add an element
my_list.extend([7, 8]) # Extend with another list
my_list.insert(0, 0) # Insert at the beginning
my_list.remove(3) # Remove first occurrence of 3
my_list.pop() # Remove and return the last item
my_list.clear() # Empty the list
克隆列表
original = [1, 2, 3]
clone = original[:] # Shallow copy using slicing
# or
clone = list(original) # Using the list constructor
第2部分:元组 – 高级概念
元组解包
point = (10, 20)
x, y = point
带 * 的元组(扩展解包)
numbers = (1, 2, 3, 4, 5)
first, *middle, last = numbers
为什么元组更快?
- 不可变 → 存储在连续内存中
- 比列表迭代更快
- 适用于固定数据(例如纬度/经度、配置)
将列表转换为元组
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
第3部分:集合 – 高级概念
集合操作
A = {1, 2, 3}
B = {3, 4, 5}
print(A | B) # union -> {1, 2, 3, 4, 5}
print(A & B) # intersection -> {3}
print(A - B) # difference -> {1, 2}
使用集合去除列表中的重复项
my_list = [1, 2, 2, 3, 4, 4]
unique = list(set(my_list)) # [1, 2, 3, 4] (order not guaranteed)
添加和删除元素
s = {1, 2, 3}
s.add(4) # {1, 2, 3, 4}
s.discard(2) # {1, 3, 4}
s.remove(3) # {1, 4}
集合推导式
squared = {x**2 for x in range(5)} # {0, 1, 4, 9, 16}
第4部分:字典 – 高级概念
字典推导式
squares = {x: x*x for x in range(5)} # {0:0, 1:1, 2:4, 3:9, 4:16}
遍历字典
d = {'a': 1, 'b': 2}
for key, value in d.items():
print(key, value)
合并两个字典
d1 = {'a': 1, 'b': 2}
d2 = {'b': 3, 'c': 4}
merged = {**d1, **d2} # {'a': 1, 'b': 3, 'c': 4}
# Python 3.9+ alternative:
merged = d1 | d2
字典方法
dict.get(key, default)dict.keys(),dict.values(),dict.items()dict.update(other_dict)dict.pop(key),dict.popitem()dict.clear()
将字典用作计数器
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
counter = {}
for w in words:
counter[w] = counter.get(w, 0) + 1
# counter -> {'apple': 3, 'banana': 2, 'orange': 1}
第5部分:Collections 模块(面试必备)
Counter(计数器)
from collections import Counter
cnt = Counter(['a', 'b', 'a', 'c', 'b', 'a'])
# Counter({'a': 3, 'b': 2, 'c': 1})
defaultdict(默认字典)
from collections import defaultdict
dd = defaultdict(list)
dd['key'].append(1) # automatically creates a list for 'key'
deque(双端队列)
from collections import deque
dq = deque([1, 2, 3])
dq.appendleft(0) # deque([0, 1, 2, 3])
dq.pop() # 3
OrderedDict(有序字典)
from collections import OrderedDict
od = OrderedDict()
od['first'] = 1
od['second'] = 2
# Preserves insertion order (Python 3.7+ dict does this by default)
第6部分:使用 Collections 的面试题程序
找出出现次数最多的元素
from collections import Counter
def most_common(lst):
return Counter(lst).most_common(1)[0][0]
print(most_common([1, 2, 2, 3, 3, 3])) # 3
在不使用 reverse() 的情况下反转列表
lst = [1, 2, 3, 4]
reversed_lst = lst[::-1] # [4, 3, 2, 1]
将两个列表合并为字典
keys = ['a', 'b', 'c']
values = [1, 2, 3]
merged_dict = dict(zip(keys, values)) # {'a': 1, 'b': 2, 'c': 3}
在保留顺序的同时去除重复项
def dedupe(seq):
seen = set()
return [x for x in seq if not (x in seen or seen.add(x))]
print(dedupe([3, 1, 2, 3, 2, 1])) # [3, 1, 2]
将字典转换为元组列表
d = {"a": 1, "b": 2}
print(list(d.items())) # [('a', 1), ('b', 2)]