Python 中的数组
Python中的list是一种动态数组,可以存储不同类型的数据。list的大小是可变的
# 定义一个列表
fruits = ["apple", "banana", "cherry", "date"]
# 访问列表中的元素
print("第一个水果是:", fruits[0]) # 输出: 第一个水果是: apple
# 修改列表中的元素
fruits[1] = "blueberry" # 将第二个元素修改为 "blueberry"
print("修改后的列表:", fruits)
# 输出: 修改后的列表: ['apple', 'blueberry', 'cherry', 'date']
# 添加元素到列表末尾(数组的大小会变化)
fruits.append("elderberry")
print("添加元素后的列表:", fruits)
# 输出: 添加元素后的列表: ['apple', 'blueberry', 'cherry', 'date', 'elderberry']
# 插入元素到列表指定位置(数组的大小会变化)
fruits.insert(2, "fig")
print("插入元素后的列表:", fruits)
# 输出: 插入元素后的列表: ['apple', 'blueberry', 'fig', 'cherry', 'date', 'elderberry']
# 删除列表中的元素
del fruits[3] # 删除索引为3的元素
print("删除元素后的列表:", fruits)
# 输出: 删除元素后的列表: ['apple', 'blueberry', 'fig', 'date', 'elderberry']
# 列表切片
sliced_fruits = fruits[1:4] # 获取索引1到3的元素(不包括索引4)
print("切片后的列表:", sliced_fruits)
# 输出: 切片后的列表: ['blueberry', 'fig', 'date']
# 列表推导式
even_numbers = [x for x in range(10) if x % 2 == 0]
print("偶数列表:", even_numbers)
# 输出: 偶数列表: [0, 2, 4, 6, 8]
# 列表排序
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_numbers = sorted(numbers)
print("排序后的列表:", sorted_numbers)
# 输出: 排序后的列表: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
# 列表反转
reversed_numbers = numbers[::-1]
print("反转后的列表:", reversed_numbers)
# 输出: 反转后的列表: [5, 3, 6, 5, 5, 9, 4, 1, 3, 1, 2]
Python 中的字典
Python的字典是使用哈希表实现的,但Python的字典还提供了额外的功能,如自动扩容、键的排序。
# 定义一个字典
person = {
"name": "John",
"age": 30,
"city": "New York"
}
# 访问字典中的值
print("姓名:", person["name"])
# 输出: 姓名: John
# 修改字典中的值
person["age"] = 31 # 修改年龄为31
print("修改后的字典:", person)
# 输出: 修改后的字典: {'name': 'John', 'age': 31, 'city': 'New York'}
# 添加新的键值对到字典
person["email"] = "john@example.com"
print("添加新键值对后的字典:", person)
# 输出: 添加新键值对后的字典: {'name': 'John', 'age': 31, 'city': 'New York', 'email': 'john@example.com'}
# 删除字典中的键值对
del person["city"] # 删除 "city" 键
print("删除键值对后的字典:", person)
# 输出: 删除键值对后的字典: {'name': 'John', 'age': 31, 'email': 'john@example.com'}
# 获取字典中所有的键
keys = person.keys()
print("字典中的键:", list(keys))
# 输出: 字典中的键: ['name', 'age', 'email']
# 获取字典中所有的值
values = person.values()
print("字典中的值:", list(values))
# 输出: 字典中的值: ['John', 31, 'john@example.com']
# 获取字典中所有的键值对
items = person.items()
print("字典中的键值对:", list(items))
# 输出: 字典中的键值对: [('name', 'John'), ('age', 31), ('email', 'john@example.com')]
# 字典推导式
squares = {x: x**2 for x in range(1, 6)}
print("平方数字典:", squares)
# 输出: 平方数字典: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# 字典排序(按键)
sorted_person = dict(sorted(person.items(), key=lambda item: item[0]))
print("按键排序后的字典:", sorted_person)
# 输出: 按键排序后的字典: {'age': 31, 'email': 'john@example.com', 'name': 'John'}
# 字典排序(按值)
sorted_person_by_value = dict(sorted(person.items(), key=lambda item: item[1]))
print("按值排序后的字典:", sorted_person_by_value)
# 输出: 按值排序后的字典: {'email': 'john@example.com', 'name': 'John', 'age': 31}
实战:两数之和
数组实现
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
arr =[0,0]
length = len(nums)
for i in range(length):
if target < nums[i]:
break
else:current = nums[i]
for j in range(i+1, length):
if nums[j] + nums[i] == target:
arr =[j,i]
return(arr)
字典实现
enumerate方法
如果数组是 [2, 7, 11, 15],enumerate(nums) 会依次返回 (0, 2)、(1, 7)、(2, 11)、(3, 15)。
# 创建一个字典来存储数组中的值和对应的索引
num_to_index = {}
# 遍历数组
for index, num in enumerate(nums):
# 计算当前数的补数(即 target - num)
complement = target - num
# 检查补数是否已经在字典中
if complement in num_to_index:
# 如果在字典中,说明找到了两个数的和为目标值
return [num_to_index[complement], index]
# 如果没有找到,将当前数及其索引存入字典
num_to_index[num] = index
# 如果遍历完数组都没有找到,抛出异常或返回空列表
raise ValueError("No two sum solution")