lst = []
lst
[]
lst = list()
lst
[]
[1]
[1]
[2,3,"AAA"] #元素类型可以不一样
[2, 3, 'AAA']
list("hello") #字符串可以转换成列表
['h', 'e', 'l', 'l', 'o']
LSTasdfafed = [1,2,3]
LSTasdfafed
[1, 2, 3]
上面是创建列表
[1,4,12,3]+[5,3]
[1, 4, 12, 3, 5, 3]
[1,4,6]*2
[1, 4, 6, 1, 4, 6]
list1 = [1,2,4,56,12]
for numm in list1:
print(numm+5)
6
7
9
61
17
LST = [1,5,6]
7in LST
False
list2 = [1,3,5]
list2
[1, 3, 5]
list2.append(32) #末尾插入数据
list2
[1, 3, 5, 32]
list2 #索引从0开始 ,所以第一个元素的索引是0 ,第二个元素的索引是1 ,以此类推
[1, 3, 5, 32]
list2.index(1) #返回元素的索引位置
0
list2.index(32) #返回元素的索引位置
3
list3 = [1,3,5,3,7,9]
list3.count(3)#统计元素出现次数
# print(list3.count(3))
2
list3.count(111)
0
del list3[2] #删除指定位置元素
list3
[1, 3, 3, 7, 9]
list3.remove(7) #删除指定元素
list3
[1, 3, 3, 9]
list2 = [1,3,5]
list2
[1, 3, 5]
list3
[1, 3, 3, 9]
list2.append(list3)
list2
[1, 3, 5, [1, 3, 3, 9]]
list2[3]
[1, 3, 3, 9]
list2.extend(list3) #将list3中的元素添加到list2的末尾
list2
[1, 3, 5, [1, 3, 3, 9], 1, 3, 3, 9]
list3
[1, 3, 3, 9]
list3.insert(1,6) #在指定索引位置插入元素
list3
[1, 6, 3, 3, 9]
len(list3) #列表长度
5
list3
[1, 6, 3, 3, 9]
list3.pop(1) #删除list3中索引为1的元素
6
list3
[1, 3, 3, 9]
list3.pop(2)
3
list3
[1, 3, 9]
list3.reverse() # reverse()方法作用颠倒元素
list3
[9, 3, 1]
list1 = [1,2,5,10,9]
list1.sort() #排序
list1
[1, 2, 5, 9, 10]
list1[1:3] #返回索引为1和2的元素
[2, 5]
list1
[1, 2, 5, 9, 10]
list1[1:4] #左闭又开 [ ) 把索引为1 2 3 的元素取出来
[2, 5, 9]
list1[:5]
[1, 2, 5, 9, 10]
aba = range(1,11) #左闭右开
aba
range(1, 11)
a = list(aba)
a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
lis2 = range(1,10,3) #左闭右开
lis2
range(1, 10, 3)
a = list(range(1,10,3))
print(a)
[1, 4, 7]
list(range(1,10,2))
[1, 3, 5, 7, 9]
b = list(lis2)
b
[1, 4, 7]
list3 = [[1,2,3],
[4,5,6],[7,8,9]]
list3
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
a = ("苹果","香蕉","橘子")
b = ["苹果","香蕉","橘子"]
type(a)
tuple
type(b)
list
type(("苹果","香蕉","橘子"))
tuple
type("123")
str
a = (1,2,3) #元组
a
(1, 2, 3)
type(a)
tuple
a = (1)
a = 1
type(a)
int
b = ("hellp",)
type(b)
tuple
b = (1,)
type(b)
tuple
tuple([1,5])
(1, 5)
a = tuple(range(10))
a
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
len(a)
10
9in a
print(9in a)
True
a.count(5)
1
a
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
list(a) #元组转换成列表
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
元组不支持如下操作
append:向序列末尾添加元素。
remove:从序列中删除指定元素。
insert:在指定位置插入元素。
reverse:反转序列元素的顺序。
sort:对序列元素进行排序。
dic = dict() #字典
dic
{}
dic = {}
dic
{}
dic = {"name":"zhangsan","age":20} #键值
dic
{'name': 'zhangsan', 'age': 20}
dic["score"] = 10#添加键值对
dic
{'name': 'zhangsan', 'age': 20, 'score': 10}
dic["age"] = 29#修改键值对
dic
{'name': 'zhangsan', 'age': 29, 'score': 10}
dic.keys()
dict_keys(['name', 'age', 'score'])
dic.values()
dict_values(['zhangsan', 29, 10])
dic["age"]
29
dic
{'name': 'zhangsan', 'age': 29, 'score': 10}
d = dic.copy() #浅拷贝
d
{'name': 'zhangsan', 'age': 29, 'score': 10}
del dic["score"] #删除指定键值对
dic
{'name': 'zhangsan', 'age': 29}
dic.items()
dict_items([('name', 'zhangsan'), ('age', 29)])
dct = {"学号":"001","姓名":"张三","年龄":20}
dct
{'学号': '001', '姓名': '张三', '年龄': 20}
dic1 = {"学号":"002","年龄":22}
dct.update(dic1)
dct
{'学号': '002', '姓名': '张三', '年龄': 22}
a = set()
a
set()
{1,2,3,3} #创建3个元素的集和
{1, 2, 3}
a = [1,4,120,4]
a
[1, 4, 120, 4]
b = set(a)
b
{1, 4, 120}
list(b)
[120, 1, 4]
set([1,4,120])
{1, 4, 120}
type(set([1,4,120]))
set
a1 = {"a","b","c"}
a1
{'a', 'b', 'c'}
for x in a1:
print(x)
c
b
a
a1.add("hh") #添加元素
a1
{'a', 'b', 'c', 'hh'}
a1.remove("b")
a1
{'a', 'c', 'hh'}
a1.clear()
a1
set()
len(a1)
0
s1 = {1,2,3,4}
s2 = {3,4,5,6}
s1 & s2 # 交集
{3, 4}
s1 | s2 # 并集
{1, 2, 3, 4, 5, 6}
s1 - s2 # 差集
{1, 2}
s2 - s1
{5, 6}
s1 == s2
False
在Python编程语言中,数据类型可以分为可变类型和不可变类型。这两种类型的主要区别在于它们是否允许变量的值在其内存地址不变的情况下被修改。
可变类型(Mutable types)是指那些可以在不更改对象内存地址的情况下更改其内容的数据类型。Python中的可变类型包括:
列表(List):可以添加、删除或更改其元素。
字典(Dictionary):可以添加新的键值对或更改现有键值对的值。
集合(Set):可以添加或删除元素。
例如,当你对列表添加一个元素时,列表的内容会改变,但其内存地址保持不变。
my_list = [1, 2, 3]
id(my_list) #
1929398424960
my_list.append(4)
my_list
[1, 2, 3, 4]
id(my_list)
1929398424960
# 创建一个字典
my_dict = {'name': 'Alice', 'age': 25}
print(my_dict)
id(my_dict) #
{'name': 'Alice', 'age': 25}
1929398256320
# 可以修改字典的值
my_dict['age'] = 30
# 可以添加新的键值对
my_dict['gender'] = 'female'
print(my_dict)
{'name': 'Alice', 'age': 30, 'gender': 'female'}
id(my_dict)
1929398256320
不可变类型(Immutable types)是指一旦创建就不能更改的数据类型。Python中的不可变类型包括:
数字(Number):如整数和浮点数。
字符串(String):创建后不能更改。
元组(Tuple):一旦创建就不能修改其内容。
例如,当尝试更改字符串中的一个字符时,Python会创建一个新的字符串对象,而原来的字符串保持不变。
my_string = "hello"
id(my_string)
1929389069808
my_string += " world"
my_string
'hello world'
print(id(my_string)) # 输出为一个新的内存地址
1929398270832
内存地址和数据的关系
在Python中,每个对象都存储在内存中,并且每个对象都有一个唯一的内存地址。不可变类型的对象在值改变时会创建一个新的对象,因此内存地址会改变。而可变类型的对象在值改变时不会创建新的对象,所以内存地址不变。
# 基本语法:[表达式 for 变量 in 可迭代对象 if 条件]
# 示例1:创建平方数列表
squares = [x**2for x inrange(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
[1, 4, 9, 16, 25]
# 示例2:带条件的筛选
even_squares = [x**2for x inrange(10) if x % 2 == 0]
print(even_squares) # [0, 4, 16, 36, 64]
[0, 4, 16, 36, 64]
# 示例3:字符串处理
words = ["hello", "world", "python"]
upper_words = [a.upper() for a in words]
print(upper_words) # ['HELLO', 'WORLD', 'PYTHON']
['HELLO', 'WORLD', 'PYTHON']
# 基本语法:{键表达式: 值表达式 for 变量 in 可迭代对象 if 条件}
# 示例1:创建数字到平方的映射
squares_dict = {x: x**2for x inrange(1, 6)}
print(squares_dict) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# 示例2:转换键值对
old_dict = {'a': 1, 'b': 2, 'c': 3}
old_dict.items()
dict_items([('a', 1), ('b', 2), ('c', 3)])
new_dict = {k:v*2for k, v in old_dict.items()}
print(new_dict)
{'a': 2, 'b': 4, 'c': 6}
# 示例3:筛选特定项
numbers = [1, 2, 3, 4, 5]
even_squares = {x: x**2for x in numbers if x % 2 == 0}
print(even_squares) # {2: 4, 4: 16}
{2: 4, 4: 16}
集合推导式用于创建集合(自动去重):
# 基本语法:{表达式 for 变量 in 可迭代对象 if 条件}
# 示例1:创建唯一平方数集合
numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
unique_squares = {x**2for x in numbers}
print(unique_squares) # {1, 4, 9, 16} # 自动去重
{16, 1, 4, 9}
# 示例2:字符串处理
words = ["apple", "banana", "apple", "cherry"]
unique_lengths = {len(word) for word in words}
print(unique_lengths) # {5, 6} # 只有两个不同的长度
{5, 6}
生成器推导式用于创建生成器(惰性计算,节省内存):
# 基本语法:(表达式 for 变量 in 可迭代对象 if 条件)
# 示例:创建平方数生成器
squares_gen = (x**2for x inrange(1000000)) # 几乎不占内存!
squares_gen
<generator object <genexpr> at 0x000001C1391176B0>
# 使用生成器
for i, square inenumerate(squares_gen):
print(square)
if i >= 4: # 只取前5个
break
# 输出: 0, 1, 4, 9, 16
0
1
4
9
16
# 二维矩阵展平
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10,11,12]]
flattened = [num for row in matrix for num in row]
print(flattened)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
# 理解嵌套顺序:从左到右,就像写嵌套循环
# 等价于:
result = []
for row in matrix:
for num in row:
result.append(num)
result
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
使用zip函数与推导式结合,可以并行处理多个列表:
names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]
# 创建姓名到分数的映射
score_dict = {x: y for x, y inzip(names, scores)}
print(score_dict) # {'Alice': 85, 'Bob': 92, 'Charlie': 78}
{'Alice': 85, 'Bob': 92, 'Charlie': 78}
# 筛选及格的学生
passing_students = [name for name, score inzip(names, scores) if score >= 80]
print(passing_students) # ['Alice', 'Bob']
['Alice', 'Bob']
# 同时处理三个列表
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
scores = [85, 92, 78]
student_info = [
{"name": name, "age": age, "score": score}
for name, age, score inzip(names, ages, scores)
if score >= 80
]
print(student_info)
# [{'name': 'Alice', 'age': 25, 'score': 85},
# {'name': 'Bob', 'age': 30, 'score': 92}]
[{'name': 'Alice', 'age': 25, 'score': 85}, {'name': 'Bob', 'age': 30, 'score': 92}]
• 列表推导式用于创建列表:[x for x in …]
• 字典推导式用于创建字典:{k: v for …}
• 集合推导式用于创建集合:{x for x in …}
• 生成器推导式用于惰性计算:(x for x in …)