Python3 datastructure

MasterPython3 list, dictionary, 元组, collectionetc.datastructure

1. list (List)

list is Pythonin最常用 datastructure之一, 它 is a has 序 可变序列, 可以store任意class型 元素.

1.1 list creation

可以using方括号[] or list()functioncreationlist.

# creationlist
empty_list = []
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed = [1, "apple", 3.14, True]

# usinglist()functioncreationlist
string_list = list("Hello")  # ['H', 'e', 'l', 'l', 'o']
range_list = list(range(5))  # [0, 1, 2, 3, 4]

print(numbers)
print(fruits)
print(mixed)

1.2 list 访问

可以usingindex访问listin 元素, index from 0开始.

# 访问list元素
fruits = ["apple", "banana", "cherry"]

print(fruits[0])    # 第一个元素
print(fruits[1])    # 第二个元素
print(fruits[2])    # 第三个元素
print(fruits[-1])   # 最 after 一个元素
print(fruits[-2])   # 倒数第二个元素

# 切片operation
print(fruits[0:2])  #  from index0 to 1 元素
print(fruits[1:])   #  from index1 to 末尾 元素
print(fruits[:2])   #  from 开头 to index1 元素
print(fruits[::2])  # 每隔一个元素取一个

1.3 list modify

list is 可变 , 可以modify, 添加 or delete元素.

# modifylist元素
fruits = ["apple", "banana", "cherry"]
fruits[1] = "orange"
print(fruits)  # ['apple', 'orange', 'cherry']

# 添加元素
fruits.append("grape")  #  in 末尾添加
print(fruits)  # ['apple', 'orange', 'cherry', 'grape']

fruits.insert(1, "pear")  #  in 指定位置插入
print(fruits)  # ['apple', 'pear', 'orange', 'cherry', 'grape']

# mergelist
more_fruits = ["kiwi", "mango"]
fruits.extend(more_fruits)
print(fruits)  # ['apple', 'pear', 'orange', 'cherry', 'grape', 'kiwi', 'mango']

# delete元素
fruits.remove("orange")  # delete指定值 元素
print(fruits)  # ['apple', 'pear', 'cherry', 'grape', 'kiwi', 'mango']

popped = fruits.pop()  # delete并返回最 after 一个元素
print(popped)  # 'mango'
print(fruits)  # ['apple', 'pear', 'cherry', 'grape', 'kiwi']

fruits.pop(1)  # delete并返回指定index 元素
print(fruits)  # ['apple', 'cherry', 'grape', 'kiwi']

# 清空list
fruits.clear()
print(fruits)  # []

1.4 list 常用method

# list 常用method
numbers = [3, 1, 4, 1, 5, 9, 2, 6]

# sort
numbers.sort()
print(numbers)  # [1, 1, 2, 3, 4, 5, 6, 9]

# 反转
numbers.reverse()
print(numbers)  # [9, 6, 5, 4, 3, 2, 1, 1]

# 计数
count = numbers.count(1)
print(count)  # 2

# findindex
index = numbers.index(5)
print(index)  # 2

# copy
numbers_copy = numbers.copy()
print(numbers_copy)  # [9, 6, 5, 4, 3, 2, 1, 1]

2. 元组 (Tuple)

元组 is a has 序 不可变序列, and listclass似, 但元组一旦creation就不能modify.

2.1 元组 creation

可以using圆括号() or tuple()functioncreation元组.

# creation元组
empty_tuple = ()
single_element = (42,)
numbers = (1, 2, 3, 4, 5)
fruits = ("apple", "banana", "cherry")
mixed = (1, "apple", 3.14, True)

# usingtuple()functioncreation元组
string_tuple = tuple("Hello")  # ('H', 'e', 'l', 'l', 'o')
list_tuple = tuple([1, 2, 3])  # (1, 2, 3)

print(numbers)
print(fruits)
print(mixed)

2.2 元组 访问

可以usingindex访问元组in 元素, and listclass似.

# 访问元组元素
fruits = ("apple", "banana", "cherry")

print(fruits[0])    # 第一个元素
print(fruits[1])    # 第二个元素
print(fruits[2])    # 第三个元素
print(fruits[-1])   # 最 after 一个元素
print(fruits[-2])   # 倒数第二个元素

# 切片operation
print(fruits[0:2])  #  from index0 to 1 元素
print(fruits[1:])   #  from index1 to 末尾 元素
print(fruits[:2])   #  from 开头 to index1 元素
print(fruits[::2])  # 每隔一个元素取一个

2.3 元组 特点

  • 不可变性: 元组creation after 不能modify元素
  • has 序性: 元组in 元素 has 固定 顺序
  • 可哈希性: 元组可以serving asdictionary 键
  • store任意class型: 可以store不同class型 元素

3. dictionary (Dictionary)

dictionary is Pythonin另一个 important datastructure, 它 is a 无序 键值 for collection, 键必须 is 唯一 且不可变 .

3.1 dictionary creation

可以using花括号{} or dict()functioncreationdictionary.

# creationdictionary
empty_dict = {}
person = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

# usingdict()functioncreationdictionary
person2 = dict(name="Bob", age=25, city="London")
person3 = dict([("name", "Charlie"), ("age", 35), ("city", "Paris")])

print(person)
print(person2)
print(person3)

3.2 dictionary 访问 and modify

可以using键访问 and modifydictionaryin 值.

# 访问dictionary值
person = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

print(person["name"])
print(person.get("age"))
print(person.get("country", "Unknown"))  # 不存 in  键, 返回默认值

# modifydictionary
person["age"] = 31  # modify现 has 键 值
person["country"] = "USA"  # 添加 new  键值 for 

print(person)

# delete键值 for 
del person["city"]
print(person)

popped_value = person.pop("age")
print(popped_value)
print(person)

# 清空dictionary
person.clear()
print(person)

3.3 dictionary 常用method

# dictionary 常用method
person = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

# 获取所 has 键
keys = person.keys()
print(list(keys))  # ['name', 'age', 'city']

# 获取所 has 值
values = person.values()
print(list(values))  # ['Alice', 30, 'New York']

# 获取所 has 键值 for 
items = person.items()
print(list(items))  # [('name', 'Alice'), ('age', 30), ('city', 'New York')]

# 遍历dictionary
for key in person:
    print(key, person[key])

for key, value in person.items():
    print(key, value)

4. collection (Set)

collection is Pythonin 一种无序且不重复 元素collection, 常用于去重 and collection运算.

4.1 collection creation

可以using花括号{} or set()functioncreationcollection.

# creationcollection
empty_set = set()  # 注意: {}creation  is dictionary
numbers = {1, 2, 3, 4, 5}
fruits = {"apple", "banana", "cherry"}

# usingset()functioncreationcollection
string_set = set("Hello")  # {'H', 'e', 'l', 'o'}
list_set = set([1, 2, 2, 3, 3, 3])  # {1, 2, 3}

print(numbers)
print(fruits)
print(string_set)

4.2 collection operation

# collection operation
numbers1 = {1, 2, 3, 4, 5}
numbers2 = {4, 5, 6, 7, 8}

# 添加元素
numbers1.add(6)
print(numbers1)  # {1, 2, 3, 4, 5, 6}

# delete元素
numbers1.remove(6)  # such as果元素不存 in , 会抛出error
print(numbers1)  # {1, 2, 3, 4, 5}

numbers1.discard(5)  # such as果元素不存 in , 不会抛出error
print(numbers1)  # {1, 2, 3, 4}

popped = numbers1.pop()  # 随机delete并返回一个元素
print(popped)
print(numbers1)  # {2, 3, 4}

# 清空collection
numbers1.clear()
print(numbers1)  # set()

# collection运算
numbers1 = {1, 2, 3, 4, 5}
numbers2 = {4, 5, 6, 7, 8}

# 并集
union = numbers1 | numbers2
print(union)  # {1, 2, 3, 4, 5, 6, 7, 8}

# 交集
intersection = numbers1 & numbers2
print(intersection)  # {4, 5}

# 差集
difference = numbers1 - numbers2
print(difference)  # {1, 2, 3}

#  for 称差集
symmetric_difference = numbers1 ^ numbers2
print(symmetric_difference)  # {1, 2, 3, 6, 7, 8}

实践case: 学生成绩management

writing一个Python程序, management学生 成绩. 程序应该:

  1. store学生 姓名 and 成绩
  2. 计算平均成绩
  3. 找出最 high 分 and 最 low 分
  4. 按成绩sort
# 学生成绩management
students = {
    "Alice": 85,
    "Bob": 92,
    "Charlie": 78,
    "David": 95,
    "Eve": 88
}

# 计算平均成绩
total = sum(students.values())
average = total / len(students)
print(f"平均成绩: {average:.2f}")

# 找出最 high 分 and 最 low 分
highest_score = max(students.values())
lowest_score = min(students.values())

# 找出最 high 分 and 最 low 分 学生
top_students = [name for name, score in students.items() if score == highest_score]
bottom_students = [name for name, score in students.items() if score == lowest_score]

print(f"最 high 分: {highest_score} (学生: {', '.join(top_students)})")
print(f"最 low 分: {lowest_score} (学生: {', '.join(bottom_students)})")

# 按成绩sort
sorted_students = sorted(students.items(), key=lambda x: x[1], reverse=True)
print("按成绩sort:")
for name, score in sorted_students:
    print(f"{name}: {score}")

互动练习: datastructure练习

1. 请writing一个程序, usingliststore10个随机数, 然 after 计算它们 and , 平均值, 最 big 值 and 最 small 值.
2. 请writing一个程序, usingdictionarystore学生 姓名 and 成绩, 然 after 找出成绩 in 90分以 on 学生.
3. 请writing一个程序, usingcollection for listin 元素for去重.

5. datastructure 选择

选择合适 datastructure for 于writing high 效 Python程序非常 important . 以 under is 一些选择datastructure 建议:

  • list: 当需要 has 序且可变 元素collection时using
  • 元组: 当需要 has 序且不可变 元素collection时using
  • dictionary: 当需要键值 for map时using
  • collection: 当需要无序且不重复 元素collection时using