列表(List)是Python中最常用的数据结构之一,它是一个可变的、有序的元素集合。
最常见的创建列表的方式是使用方括号:
list1 = [1, 2, 3, 4, 5]
list2 = ['a', 'b', 'c']
list3 = [1, 'hello', 3.14, True]
可以使用list()函数将其他可迭代对象转换为列表:
tuple1 = (1, 2, 3)
list4 = list(tuple1)
string1 = "hello"
list5 = list(string1) # ['h', 'e', 'l', 'l', 'o']
列表推导式提供了一种简洁的方式来创建列表:
squares = [x**2 for x in range(10)]
使用索引可以访问列表中的单个元素:
list1 = [10, 20, 30, 40, 50]
print(list1[0]) # 输出: 10
print(list1[-1]) # 输出: 50
可以使用切片操作来访问列表的一部分:
list1 = [10, 20, 30, 40, 50]
print(list1[1:3]) # 输出: [20, 30]
print(list1[:3]) # 输出: [10, 20, 30]
print(list1[2:]) # 输出: [30, 40, 50]
print(list1[::2]) # 输出: [10, 30, 50]
list1 = [1, 2, 3]
list1.append(4)
list1.insert(0, 0)
list1.extend([5, 6])
print(list1) # 输出: [0, 1, 2, 3, 4, 5, 6]
list1 = [1, 2, 3, 2, 4]
list1.remove(2)
popped = list1.pop(1)
del list1[0]
print(list1) # 输出: [2, 4]
可以直接通过索引修改列表元素:
list1 = [1, 2, 3]
list1[1] = 20
print(list1) # 输出: [1, 20, 3]
使用+运算符连接列表,使用*运算符重复列表:
list1 = [1, 2]
list2 = [3, 4]
list3 = list1 + list2
list4 = list1 * 3
print(list3) # 输出: [1, 2, 3, 4]
print(list4) # 输出: [1, 2, 1, 2, 1, 2]
Python列表提供了多种内置方法:
list1 = [3, 1, 4, 1, 5, 9, 2]
list1.sort()
print(list1) # 输出: [1, 1, 2, 3, 4, 5, 9]
list1.reverse()
print(list1) # 输出: [9, 5, 4, 3, 2, 1, 1]
print(list1.count(1)) # 输出: 2
print(list1.index(4)) # 输出: 2
list1.clear()
print(list1) # 输出: []
可以将列表中的元素解包到多个变量中:
list1 = [1, 2, 3]
a, b, c = list1
print(a, b, c) # 输出: 1 2 3
# 使用*解包剩余元素
list2 = [1, 2, 3, 4, 5]
first, *middle, last = list2
print(first, middle, last) # 输出: 1 [2, 3, 4] 5
列表推导式提供了一种简洁的方式来创建列表:
squares = [x**2 for x in range(10)]
even_squares = [x**2 for x in range(10) if x % 2 == 0]
生成器表达式类似于列表推导式,但它们返回一个生成器对象:
gen = (x**2 for x in range(10))
列表可以用作栈(后进先出)或队列(先进先出):
# 栈
stack = []
stack.append(1)
stack.append(2)
print(stack.pop()) # 输出: 2
# 队列
from collections import deque
queue = deque([])
queue.append(1)
queue.append(2)
print(queue.popleft()) # 输出: 1
列表的列表可以表示矩阵:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[1][1]) # 输出: 5
对于大量数据或频繁的插入/删除操作,可能需要考虑使用其他数据结构,如deque。
元组(tuple)是Python中的一种基本数据结构,与列表类似,但元组是不可变的。虽然它们看似简单,但在适当的场景下使用元组可以带来诸多好处,如提高代码的可读性和执行效率。
最常见的创建元组的方式是使用圆括号:
tup1 = (1, 2, 3)
tup2 = ('a', 'b', 'c')
Python也允许省略圆括号来创建元组:
tup3 = 1, 2, 3
tup4 = 'a', 'b', 'c'
可以使用tuple()函数将其他可迭代对象转换为元组:
list1 = [1, 2, 3]
tup5 = tuple(list1)
创建只包含一个元素的元组时,需要在元素后加一个逗号:
tup6 = (42,) # 正确
tup7 = (42) # 错误,这是一个整数
使用索引可以访问元组中的单个元素:
tup = (1, 2, 3, 4, 5)
print(tup[0]) # 输出: 1
print(tup[-1]) # 输出: 5
可以使用切片操作来访问元组的一部分:
tup = (1, 2, 3, 4, 5)
print(tup[1:3]) # 输出: (2, 3)
print(tup[:3]) # 输出: (1, 2, 3)
print(tup[2:]) # 输出: (3, 4, 5)
可以使用+运算符连接两个或多个元组:
tup1 = (1, 2, 3)
tup2 = (4, 5, 6)
tup3 = tup1 + tup2
print(tup3) # 输出: (1, 2, 3, 4, 5, 6)
使用*运算符可以重复元组:
tup = (1, 2) * 3
print(tup) # 输出: (1, 2, 1, 2, 1, 2)
可以将元组中的元素解包到多个变量中:
tup = (1, 2, 3)
a, b, c = tup
print(a, b, c) # 输出: 1 2 3
虽然元组是不可变的,但它们仍然有一些内置方法:
返回指定元素在元组中出现的次数:
tup = (1, 2, 2, 3, 2)
print(tup.count(2)) # 输出: 3
返回指定元素在元组中首次出现的索引:
tup = (1, 2, 3, 2)
print(tup.index(2)) # 输出: 1
元组的一个关键特性是不可变性。这意味着一旦创建,就不能修改元组的内容:
tup = (1, 2, 3)
# tup[0] = 4 # 这会引发TypeError
然而,如果元组包含可变对象(如列表),这些对象的内容可以被修改:
tup = ([1, 2], [3, 4])
tup[0][0] = 5
print(tup) # 输出: ([5, 2], [3, 4])
函数可以使用元组来返回多个值:
def get_coordinates():
return (10, 20)
x, y = get_coordinates()
元组可以作为字典的键,而列表不行:
dict1 = {(1, 2): 'value'}
由于元组是不可变的,它们可以用来存储不应被修改的数据:
DAYS = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
元组和列表有很多相似之处,但也有一些关键区别:
字典是Python中最有用和最灵活的数据结构之一。它允许我们存储键值对,并通过键快速访问、修改或删除值。本文将全面介绍Python字典的创建、基本操作、高级技巧以及最佳实践。
在Python中创建字典有多种方法:
# 使用花括号
dict1 = {'name': 'Alice', 'age': 25}
# 使用dict()函数
dict2 = dict(name='Bob', age=30)
# 使用列表的键值对
dict3 = dict([('name', 'Charlie'), ('age', 35)])
# 使用字典推导式
dict4 = {x: x**2 for x in range(5)}
my_dict = {'name': 'David', 'age': 40}
# 使用键访问值
print(my_dict['name']) # 输出: David
# 使用get()方法(推荐,因为它可以提供默认值)
print(my_dict.get('age', 0)) # 输出: 40
print(my_dict.get('height', 180)) # 输出: 180 (默认值)
my_dict = {'name': 'Eva', 'age': 45}
# 修改现有键的值
my_dict['age'] = 46
# 添加新的键值对
my_dict['city'] = 'New York'
print(my_dict) # 输出: {'name': 'Eva', 'age': 46, 'city': 'New York'}
my_dict = {'name': 'Frank', 'age': 50, 'city': 'Paris'}
# 使用del关键字
del my_dict['age']
# 使用pop()方法
city = my_dict.pop('city')
# 删除并返回最后插入的项
last_item = my_dict.popitem()
print(my_dict) # 输出: {}
Python字典提供了多种有用的方法:
my_dict = {'a': 1, 'b': 2, 'c': 3}
# keys(), values(), items()
print(my_dict.keys()) # 输出: dict_keys(['a', 'b', 'c'])
print(my_dict.values()) # 输出: dict_values([1, 2, 3])
print(my_dict.items()) # 输出: dict_items([('a', 1), ('b', 2), ('c', 3)])
# clear()
my_dict.clear()
print(my_dict) # 输出: {}
# copy() - 浅拷贝
original = {'x': 1, 'y': 2}
copied = original.copy()
# update()
original.update({'z': 3, 'y': 20})
print(original) # 输出: {'x': 1, 'y': 20, 'z': 3}
在Python 3.5+中,我们可以使用**
操作符来合并字典:
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
merged = {**dict1, **dict2}
print(merged) # 输出: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
defaultdict
是dict
的一个子类,它可以为不存在的键提供默认值:
from collections import defaultdict
dd = defaultdict(list)
dd['fruits'].append('apple')
dd['fruits'].append('banana')
print(dd) # 输出: defaultdict(<class 'list'>, {'fruits': ['apple', 'banana']})
从Python 3.7开始,常规字典保留了插入顺序。但对于更早的版本,我们可以使用OrderedDict
:
from collections import OrderedDict
od = OrderedDict()
od['first'] = 1
od['second'] = 2
od['third'] = 3
print(od) # 输出: OrderedDict([('first', 1), ('second', 2), ('third', 3)])
字典推导式提供了一种简洁的方式来创建字典:
squares = {x: x**2 for x in range(6)}
print(squares) # 输出: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# 条件字典推导式
even_squares = {x: x**2 for x in range(6) if x % 2 == 0}
print(even_squares) # 输出: {0: 0, 2: 4, 4: 16}
使用in
操作符检查键是否存在:
if 'key' in my_dict:
# 处理键存在的情况
使用dict.get()
方法安全地获取值,避免KeyError:
value = my_dict.get('key', default_value)
对于大型字典,使用items()
方法进行迭代更高效:
for key, value in my_dict.items():
# 处理键值对
使用collections.Counter
快速计数:
from collections import Counter
my_list = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
count_dict = Counter(my_list)
print(count_dict) # 输出: Counter({4: 4, 3: 3, 2: 2, 1: 1})
对于需要频繁修改的大型字典,考虑使用collections.defaultdict
或collections.Counter
以提高性能。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有