Home > Article > Backend Development > How to use Python's combined data types
Sequence type: Internal elements have positional relationships and can be accessed through position numbers Element
The list is a sequence type that can use multiple types of elements and supports the addition, deletion, search, and modification operations of elements
ls = ["Python", 1989, True, {"version": 3.7}] ls
['Python', 1989, True, {'version': 3.7}]
Another way to generate: list (iterable object)
Iterable objects include: strings, tuples, sets, range(), etc.
String to list
list("欢迎订阅本专栏")
['欢', '迎', '订', '阅', '本', '专', '栏']
Tuple to list
list(("我", "们", "很", "像"))
['我', '们', '很', '像']
Collection to list
list({"李雷", "韩梅梅", "Jim", "Green"})
['Green', 'Jim', '李雷', '韩梅梅']
Special range()
for i in [0, 1, 2, 3, 4, 5]: print(i)
0 1 2 3 4 5
for i in range(6): print(i)
0 1 2 3 4 5
range(start number, stop number, number interval)
If the starting number is defaulted, it defaults to 0
must include the stopping number, but note that the stopping number cannot be taken
The default number interval is 1
for i in range(1, 11, 2): print(i)
1 3 5 7 9
range() to list
list(range(1, 11, 2))
[1, 3, 5, 7, 9]
The length of the list——len(list)
ls = [1, 2, 3, 4, 5] len(ls)
5
The index of the list—— Identical to strings of the same sequence type
Variable name [position number]
Forward index starts from 0
Reverse index starts from -1
cars = ["BYD", "BMW", "AUDI", "TOYOTA"]
print(cars[0]) print(cars[-4])
BYD BYD
Slice of list
Variable name [Start position: End position: Slice Interval]
cars = ["BYD", "BMW", "AUDI", "TOYOTA"]
Forward slice
print(cars[:3]) # 前三个元素,开始位置缺省,默认为0;切片间隔缺省,默认为1
['BYD', 'BMW', 'AUDI']
print(cars[1:4:2]) # 第二个到第四个元素 前后索引差为2
['BMW', 'TOYOTA']
print(cars[:]) # 获取整个列表,结束位置缺省,默认取值到最后
['BYD', 'BMW', 'AUDI', 'TOYOTA']
print(cars[-4:-2]) # 获取前两个元素
['BYD', 'BMW']
cars = ["BYD", "BMW", "AUDI", "TOYOTA"]
print(cars[:-4:-1]) # 开始位置缺省,默认为-1 print(cars[::-1]) # 获得反向列表
['TOYOTA', 'AUDI', 'BMW'] ['TOYOTA', 'AUDI', 'BMW', 'BYD']List operators
a = [1, 2] b = [3, 4] a+b # 该用法用的不多
[1, 2, 3, 4]
Initialize one of the lists Methods
[0]*10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]List operation methods
1. Add elements
languages = ["Python", "C++", "R"]
languages.append("Java") languages
['Python', 'C++', 'R', 'Java']
at the position Number the corresponding element
before inserting the element to be added
languages.insert(1, "C") languages
['Python', 'C', 'C++', 'R', 'Java']
languages.append(["Ruby", "PHP"]) languages
['Python', 'C', 'C++', 'R', 'Java', ['Ruby', 'PHP']]
extend Add the elements in list 2 to list 1 one by one, of course This can be achieved by addition.
languages = ['Python', 'C', 'C++', 'R', 'Java'] languages.extend(["Ruby", "PHP"]) languages
['Python', 'C', 'C++', 'R', 'Java', 'Ruby', 'PHP']2. Delete the element
languages = ['Python', 'C', 'C++', 'R', 'Java'] languages.pop(1) languages
['Python', 'C++', 'R', 'Java']
languages.pop() languages
['Python', 'C++', 'R']
##
languages = ['Python', 'C', 'R', 'C', 'Java'] languages.remove("C") languages
['Python', 'R', 'C', 'Java']
languages = ['Python', 'C', 'R', 'C', 'Java'] while "C" in languages: languages.remove("C") languages
['Python', 'R', 'Java']
in the list The position where the element to be checked appears for the first time list.index(element to be checked)
languages = ['Python', 'C', 'R','Java'] idx = languages.index("R") idx
2
Modify the element through the method of "index first and then assign value" list name[position]=new value
languages = ['Python', 'C', 'R','Java'] languages[1] = "C++" languages
['Python', 'C++', 'R', 'Java']
5、列表的复制
错误的方式:这种方式仅是相当于给列表起了一个别名
languages = ['Python', 'C', 'R','Java'] languages_2 = languages print(languages_2)
['Python', 'C', 'R', 'Java']
languages.pop() print(languages) print(languages_2)
['Python', 'C', 'R'] ['Python', 'C', 'R']
正确的方式——浅拷贝
当内容中也有列表这种可变的情况时,这时浅拷贝可能出问题,应该采用深拷贝。
方法1:列表.copy()
languages = ['Python', 'C', 'R','Java'] languages_2 = languages.copy() languages.pop() print(languages) print(languages_2)
['Python', 'C', 'R'] ['Python', 'C', 'R', 'Java']
方法2:列表 [ : ]
相当于对整个列表的切片
languages = ['Python', 'C', 'R','Java'] languages_3 = languages[:] languages.pop() print(languages) print(languages_3)
['Python', 'C', 'R'] ['Python', 'C', 'R', 'Java']
6、列表的排序
使用列表.sort()对列表进行永久排序
直接在列表上进行操作,无返回值
默认是递增的排序
ls = [2, 5, 2, 8, 19, 3, 7] ls.sort() ls
[2, 2, 3, 5, 7, 8, 19]
递减排列
ls.sort(reverse = True) ls
[19, 8, 7, 5, 3, 2, 2]
使用sorted(列表)对列表进行临时排序
原列表保持不变,返回排序后的列表
ls = [2, 5, 2, 8, 19, 3, 7] ls_2 = sorted(ls) print(ls) print(ls_2)
[2, 5, 2, 8, 19, 3, 7] [19, 8, 7, 5, 3, 2, 2]
sorted(ls, reverse = True)
[19, 8, 7, 5, 3, 2, 2]
7、列表的翻转
使用列表.reverse()对列表进行永久翻转
直接在列表上进行操作,无返回值
ls = [1, 2, 3, 4, 5] print(ls[::-1]) ls
[5, 4, 3, 2, 1] [1, 2, 3, 4, 5]
ls.reverse() ls
[5, 4, 3, 2, 1]
8、使用for循环对列表进行遍历
ls = [1, 2, 3, 4, 5] for i in ls: print(i)
1 2 3 4 5
元组是一个可以使用多种类型元素,一旦定义,内部元素不支持增、删和修改操作的序列类型
通俗的讲,可以将元组视作“不可变的列表”
names = ("Peter", "Pual", "Mary")
不支持元素增加、元素删除、元素修改操作
其他操作与列表的操作完全一致
打包与解包
例1 返回值是打包成元组的形式
def f1(x): # 返回x的平方和立方 return x**2, x**3 # 实现打包返回 print(f1(3)) print(type(f1(3))) # 元组类型
(9, 27) <class 'tuple'>
a, b = f1(3) # 实现解包赋值 print(a) print(b)
9 27
例2
采用zip函数进行打包
numbers = [201901, 201902, 201903] name = ["小明", "小红", "小强"] list(zip(numbers,name))
[(201901, '小明'), (201902, '小红'), (201903, '小强')]
for number,name in zip(numbers,name): # 每次取到一个元组,立刻进行解包赋值 print(number, name)
201901 小明 201902 小红 201903 小强
映射类型: 通过“键”-“值”的映射实现数据存储和查找
常规的字典是无序的,仅可以通过键来对数据进行访问
students = {201901: '小明', 201902: '小红', 201903: '小强'} students
字典键的要求
1、字典的键不能重复
如果重复,前面的键就被覆盖了
students = {201901: '小明', 201901: '小红', 201903: '小强'} students
{201901: '小红', 201903: '小强'}
2、字典的键必须是不可变类型,如果键可变,就找不到对应存储的值了
不可变类型:数字、字符串、元组。 一旦确定,它自己就是它自己,变了就不是它了。
可变类型:列表、字典、集合。 一旦确定,还可以随意增删改。因此这三个类型不能作为字典的键。
d1 = {1: 3} d2 = {"s": 3} d3 = {(1,2,3): 3}
上面没有报错,说明是合法的。
d = {[1, 2]: 3}
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-68-bf7f06622b3f> in <module> ----> 1 d = {[1, 2]: 3} TypeError: unhashable type: 'list'
d = {{1:2}: 3}
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-69-188e5512b5fe> in <module> ----> 1 d = {{1:2}: 3} TypeError: unhashable type: 'dict'
d = {{1, 2}: 3}
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-70-c2dfafc1018a> in <module> ----> 1 d = {{1, 2}: 3} TypeError: unhashable type: 'set'
字典的长度——键值对的个数
students = {201901: '小明', 201902: '小红', 201903: '小强'} len(students)
3
字典的索引
通过 字典[键] 的形式来获取对应的值
students = {201901: '小明', 201902: '小红', 201903: '小强'} students[201902]
'小红'
1、增加键值对
变量名[新键] = 新值
students = {201901: '小明', 201902: '小红', 201903: '小强'} students[201904] = "小雪" students
{201901: '小明', 201902: '小红', 201903: '小强', 201904: '小雪'}
2、删除键值对
通过del 变量名[待删除键]
students = {201901: '小明', 201902: '小红', 201903: '小强'} del students[201903] students
{201901: '小明', 201902: '小红'}
通过变量名.pop(待删除键)
students = {201901: '小明', 201902: '小红', 201903: '小强'} value = students.pop(201903) # 删除键值对,同时获得删除键值对的值 print(value) print(students)
小强 {201901: '小明', 201902: '小红'}
变量名.popitem() 随机删除一个键值对,并以元组返回删除键值对
students = {201901: '小明', 201902: '小红', 201903: '小强'} key, value = students.popitem() print(key, value) print(students)
201903 小强 {201901: '小明', 201902: '小红'}
3、修改值
通过先索引后赋值的方式对相应的值进行修改
students = {201901: '小明', 201902: '小红', 201903: '小强'} students[201902] = "小雪" students
{201901: '小明', 201902: '小雪', 201903: '小强'}
4、d.get( )方法
d.get(key,default) 从字典d中获取键key对应的值,如果没有这个键,则返回default
小例子:统计"牛奶奶找刘奶奶买牛奶"中字符的出现频率
s = "牛奶奶找刘奶奶买牛奶" d = {} print(d) for i in s: d[i] = d.get(i, 0)+1 # 如果该字符第一次出现,则返回default 0 ,然后+1统计。如果之前就有i这个键,则返回该 key i 所对应的值。 print(d) # print(d)
{} {'牛': 1} {'牛': 1, '奶': 1} {'牛': 1, '奶': 2} {'牛': 1, '奶': 2, '找': 1} {'牛': 1, '奶': 2, '找': 1, '刘': 1} {'牛': 1, '奶': 3, '找': 1, '刘': 1} {'牛': 1, '奶': 4, '找': 1, '刘': 1} {'牛': 1, '奶': 4, '找': 1, '刘': 1, '买': 1} {'牛': 2, '奶': 4, '找': 1, '刘': 1, '买': 1} {'牛': 2, '奶': 5, '找': 1, '刘': 1, '买': 1}
5、d.keys( ) d.values( )方法
把所有的key,value 单独拿出来。
students = {201901: '小明', 201902: '小红', 201903: '小强'} print(list(students.keys())) print(list(students.values()))
[201901, 201902, 201903] ['小明', '小红', '小强']
6、d.items( )方法及字典的遍历
print(list(students.items())) for k, v in students.items():#进行解包 print(k, v)
[(201901, '小明'), (201902, '小红'), (201903, '小强')] 201901 小明 201902 小红 201903 小强
一系列互不相等元素的无序集合(互斥)
元素必须是不可变类型:数字,字符串或元组,可视作字典的键
可以看做是没有值,或者值为None的字典
students = {"小明", "小红", "小强", "小明"} #可用于去重 students
{'小强', '小明', '小红'}
小例子 通过集合进行交集并集的运算
Chinese_A = {"刘德华", "张学友", "张曼玉", "钟楚红", "古天乐", "林青霞"} Chinese_A
{'刘德华', '古天乐', '张学友', '张曼玉', '林青霞', '钟楚红'}
Math_A = {"林青霞", "郭富城", "王祖贤", "刘德华", "张曼玉", "黎明"} Math_A
{'刘德华', '张曼玉', '林青霞', '王祖贤', '郭富城', '黎明'}
语文和数学两门均为A的学员
S & T 返回一个新集合,包括同时在集合S和T中的元素
Chinese_A & Math_A
{'刘德华', '张曼玉', '林青霞'}
语文或数学至少一门为A的学员
S | T 返回一个新集合,包括集合S和T中的所有元素
Chinese_A | Math_A
{'刘德华', '古天乐', '张学友', '张曼玉', '林青霞', '王祖贤', '郭富城', '钟楚红', '黎明'}
语文数学只有一门为A的学员
S ^ T 返回一个新集合,包括集合S和T中的非共同元素
Chinese_A ^ Math_A
{'古天乐', '张学友', '王祖贤', '郭富城', '钟楚红', '黎明'}
语文为A,数学不为A的学员
S - T 返回一个新集合,包括在集合S但不在集合T中的元素
Chinese_A - Math_A
{'古天乐', '张学友', '钟楚红'}
数学为A,语文不为A的学员
Math_A - Chinese_A
{'王祖贤', '郭富城', '黎明'}
增加元素——S.add(x)
stars = {"刘德华", "张学友", "张曼玉"} stars.add("王祖贤") stars
{'刘德华', '张学友', '张曼玉', '王祖贤'}
移除元素——S.remove(x)
stars.remove("王祖贤") stars
{'刘德华', '张学友', '张曼玉'}
集合的长度——len(S)
len(stars)
3
集合的遍历——借助for循环
for star in stars: print(star)
张学友 张曼玉 刘德华
The above is the detailed content of How to use Python's combined data types. For more information, please follow other related articles on the PHP Chinese website!