列表(List):
字典(Dictionary):
列表的优势:
append()
, insert()
, remove()
, sort()
等。字典的优势:
列表的类型:
[1, 2, 3, 4]
['apple', 'banana', 'cherry']
[1, 'apple', 3.14, True]
字典的类型:
{'name': 'Alice', 'age': 25}
{1: 'one', 2: 'two'}
{(1, 2): 'pair'}
列表的应用场景:
字典的应用场景:
问题1:列表索引越界
my_list = [1, 2, 3]
print(my_list[3]) # 索引越界
解决方法:
if len(my_list) > 3:
print(my_list[3])
else:
print("Index out of range")
问题2:字典键不存在
my_dict = {'name': 'Alice'}
print(my_dict['age']) # 键不存在
解决方法:
if 'age' in my_dict:
print(my_dict['age'])
else:
print("Key not found")
问题3:列表和字典的性能优化
collections.OrderedDict
保持插入顺序,或者使用collections.defaultdict
简化默认值处理。列表操作示例:
# 创建列表
my_list = [1, 2, 3, 4, 5]
# 访问元素
print(my_list[2]) # 输出: 3
# 添加元素
my_list.append(6)
print(my_list) # 输出: [1, 2, 3, 4, 5, 6]
# 删除元素
my_list.remove(3)
print(my_list) # 输出: [1, 2, 4, 5, 6]
# 切片操作
sub_list = my_list[1:4]
print(sub_list) # 输出: [2, 4, 5]
字典操作示例:
# 创建字典
my_dict = {'name': 'Alice', 'age': 25}
# 访问值
print(my_dict['name']) # 输出: Alice
# 添加键值对
my_dict['city'] = 'New York'
print(my_dict) # 输出: {'name': 'Alice', 'age': 25, 'city': 'New York'}
# 删除键值对
del my_dict['age']
print(my_dict) # 输出: {'name': 'Alice', 'city': 'New York'}
# 检查键是否存在
if 'name' in my_dict:
print("Name exists")
通过以上内容,您可以全面了解Python中列表和字典的基础概念、优势、类型、应用场景以及常见问题的解决方法。