数值类型主要包括整数、浮点数和复数
整数类型用于表示没有小数部分的数值
x = 10
y = -5
z = 0
特点:
浮点数类型用于表示带小数部分的数值
a = 3.14
b = -2.718
c = 0.0
特点:
复数类型用于表示复数,包含实部和虚部
x = 1 + 2j
y = 3 - 4j
特点:
.real
和.imag
属性访问实部和虚部序列类型包括字符串、列表、元组等,用于存储有序的元素
字符串是字符的序列,用引号(单引号或双引号)括起来
s = "Hello, World!"
特点:
print(s[0]) # 输出: H
print(s[7:12]) # 输出: World
print(s.lower()) # 输出: hello, world!
列表是可变的有序集合,用方括号表示。列表中的元素可以是不同类型
lst = [1, 2, 3, "a", "b", "c"]
特点:
print(lst[0]) # 输出: 1
lst.append(4)
print(lst) # 输出: [1, 2, 3, 'a', 'b', 'c', 4]
lst[2] = "new"
print(lst) # 输出: [1, 2, 'new', 'a', 'b', 'c', 4]
元组是不可变的有序集合,用圆括号表示
tup = (1, 2, 3, "a")
特点:
print(tup[0]) # 输出: 1
# tup[1] = "new" # 会报错,因为元组不可变
映射类型主要包括字典(dictionary),用于存储键值对
字典是无序的键值对集合,用大括号表示
d = {'name': 'Alice', 'age': 25}
特点:
print(d['name']) # 输出: Alice
d['age'] = 26
print(d) # 输出: {'name': 'Alice', 'age': 26}
d['gender'] = 'Female'
print(d) # 输出: {'name': 'Alice', 'age': 26, 'gender': 'Female'}
集合类型包括集合(set)和冻结集合(frozenset),用于存储无序不重复的元素
s = {1, 2, 3, 4}
特点:
可以使用花括号 {}
或 set()
函数创建集合
# 使用花括号创建集合
fruits = {"apple", "banana", "cherry"}
# 使用 set() 函数创建空集合
empty_set = set()
使用 {} 创建空字典而不是集合,因此创建空集合必须使用 set() 函数
a.创建空字典
{}
创建的是一个空字典empty_dict = {}
b.创建空集合
set()
创建的是一个空集合empty_set = set()
集合支持多种操作,包括添加、删除元素以及集合运算
a.添加元素:add()
fruits.add("orange")
print(fruits) # 输出: {"apple", "banana", "cherry", "orange"}
b.删除元素:remove()
和 discard()
fruits.remove("banana")
# fruits.remove("pear") # 若元素不存在,`remove()` 将抛出 KeyError
fruits.discard("pear") # 若元素不存在,`discard()` 不会抛出错误
c.集合运算:并集、交集、差集和对称差集
# 定义两个集合
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
# 并集:所有元素的集合
union_set = set1 | set2
print(union_set) # 输出: {1, 2, 3, 4, 5, 6}
# 交集:共同元素的集合
intersection_set = set1 & set2
print(intersection_set) # 输出: {3, 4}
# 差集:在 set1 中但不在 set2 中的元素集合
difference_set = set1 - set2
print(difference_set) # 输出: {1, 2}
# 对称差集:不在交集中的元素集合
symmetric_difference_set = set1 ^ set2
print(symmetric_difference_set) # 输出: {1, 2, 5, 6}
d.数据去重:利用集合的元素唯一性,可以方便地去重
# 列表中含有重复元素
list_with_duplicates = [1, 2, 2, 3, 4, 4, 5]
# 使用集合去重
unique_elements = list(set(list_with_duplicates))
print(unique_elements) # 输出: [1, 2, 3, 4, 5]
numbers = {1, 2, 3, 4, 5}
print(3 in numbers) # 输出: True
print(6 in numbers) # 输出: False