Python:容器(列表、元组、集合、字典)

目录

前言:

一、列表(list(线性表))

二、集合(set)---哈希结构

三、元组(tuple)

四、字典(dict)

五、字符串

六、常见排序

6.1 选择排序

6.2 冒泡排序

6.3 插入排序

6.4 计数排序(桶排序)

七、切片操作


前言:

·        容器是一个可以存放多个元素的一种数据类型,弥补了变量只能存储一个元素的缺陷。容器的分类有列表、元组、集合以及字典。

一、列表(list(线性表))

常见线性表(数组、栈、队列、链表(单向链表和双向链表))属于一种数据结构,python中列表是基于链表(双向链表)实现。

定义列表方法:

第一种:根据python是弱数据类型语言特点 ls = [1,2,3,4,5]

第二种:list() ls = list() ls = list([1,2,3,4,5])

>>> ls = [1,2,3,4,5]
>>> type(ls)
<class 'list'>
>>> ls1 = list()
>>> type(ls1)
<class 'list'>
>>> ls2 = list([1,2,3,4,5,6])
>>> type(ls2)
<class 'list'>

如何访问元素?

通过下标访问元素,注意的是下标从0开始,如果下标超过范围会报错,可以通过下标改变元素的值(修 改元素),下标也可以为负数。

>>> ls
[1, 2, 3, 4, 5]
>>> ls[2]
3
>>> ls[5]
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> ls[2]
3
>>> ls[2] = 6
>>> ls
[1, 2, 6, 4, 5]
>>> ls[-1]
5
>>> ls[-5]
1
>>> ls[-6]
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
IndexError: list index out of range

如何遍历容器?

for i in ls:
    print(i)
#while 循环
index = 0
while index < len(ls):
    print(ls[index])
    index += 1

常见方法: [ 'append','clear','copy','count','extend','index','insert','pop','remove','reverse','sort']

append(object)------ 向列表尾部追加元素(添加)

>>> ls
[1, 2, 6, 4, 5]
>>> ls.append(7)
>>> ls
[1, 2, 6, 4, 5, 7]

insert(index,object) ------- 向指定位置(index)添加元素

>>> ls
[1, 2, 6, 4, 5, 7]
>>> ls.insert(3,8)
>>> ls
[1, 2, 6, 8, 4, 5, 7]

sort() ---- 列表进行排序(默认从小到大的顺序 int),其他类型也可以进行排序(按照ASCII的值),注 意排序的时候列表里元素的类型必须一致(单一)

>>> ls
[1, 2, 6, 8, 4, 5, 7]
>>> ls.sort()
>>> ls
[1, 2, 4, 5, 6, 7, 8]
>>> ls1
[]
>>> ls1 = ["A","a","D","C","e"]
>>> ls1.sort()
>>> ls1
['A', 'C', 'D', 'a', 'e']

index() -------- 查找元素的位置,返回的是下标,如果元素有重复的情况下,返回的是元素第一次出现的位 置,如果元素不存在会报错

>>> ls
[1, 2, 4, 5, 6, 7, 8]
>>> ls.index(6)
4
>>> ls.append(1)
>>> ls
[1, 2, 4, 5, 6, 7, 8, 1]
>>> ls.index(1)
0
>>> ls.index(9)
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
ValueError: 9 is not in list

reverse() ------- 将列表进行翻转

>>> ls
[1, 2, 4, 5, 6, 7, 8, 1]
>>> ls.reverse()
>>> ls
[1, 8, 7, 6, 5, 4, 2, 1]

remove() ------- 通过元素移除列表中的元素,如果元素不存在会抛出异常(报错)

>>> ls
[1, 8, 7, 6, 5, 4, 2, 1]
>>> ls.remove(2)
>>> ls
[1, 8, 7, 6, 5, 4, 1]
>>> ls.remove(9)
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list

count() ------- 统计元素在列表中出现的次数(个数)

>> ls.count(1)
2
>>> ls
[1, 8, 7, 6, 5, 4, 1]
>>> ls.count(5)
1

clear() ------- 清除元素(注意:慎用)

>>> ls
[1, 8, 7, 6, 5, 4, 1]
>>> ls.clear()
>>> ls
[]

copy() ------ 拷贝列表(浅拷贝 拷贝不等价与= 在堆内存中进行对象的拷贝)

>>> ls = [1,2,3,4,5]
>>> ls1
['A', 'C', 'D', 'a', 'e']
>>> ls.copy()
[1, 2, 3, 4, 5]
>>> ls1 = ls.copy()
>>> ls1
[1, 2, 3, 4, 5]
>>> ls
[1, 2, 3, 4, 5]

extend() ------ 合并列表

>>> ls.extend(ls1)
>>> ls
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
>>> ls1
[1, 2, 3, 4, 5]
>>> ls2
[1, 2, 3, 4, 5, 6]
>>> ls1.extend(ls2)
>>> ls1
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6]

pop() ----- 与append()相反,从列表尾部删除元素,有返回值,返回值是删除掉的这个元素,如果要删 除指定位置的元素pop(index)

>>> ls
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
>>> ls.pop()
5
>>> ls
[1, 2, 3, 4, 5, 1, 2, 3, 4]
>>> ls.pop(2)
3

补充:

1. 通过下标可以修改某个元素的值

2. 列表中的元素类型可以不同

3. 列表中的元素也可以是列表

[1, 2, 3, [1, 2, 3], 4, 5]
>>> type(ls4)
<class 'list'>
>>> ls4[3][2]
3

EG:

L = [["1","2","4"],["java","linux","HCIA","PYTHON"],[3,4,5,6]]
print(L[0][1]) ---- "2"
print(L[2][1]) --- 4
print(L[1][2]) ---- HCIA

二、集合(set)---哈希结构

创建方法:

1. s = {1,2,3,4}

2. s = set()

集合是基于哈希结构实现的

集合特点:无序的,不能重复的(无序并不是指顺序 hash底层 )

s[0] ------ 报错

常见方法: ['add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']

clear

copy

remove

add() ---- 添加元素,如果添加的元素是重复的情况下,不会报错,并且不会被二次添加 difference() ------ 差集

>>> s1 = {3,4,5,6,7,8}
>>> s1
{3, 4, 5, 6, 7, 8}
>>> s
{1, 2, 3, 4, 5}
>>> s.difference(s1)
{1, 2}
>>> s1.difference(s)
{8, 6, 7}

intersection() ------ 交集

union() ----- 并集

update() ----- 更新集合,合并集合

>>> s
{1, 2, 3, 4, 5}
>>> s1
{3, 4, 5, 6, 7, 8}
>>> s.update(s1)
>>> s
{1, 2, 3, 4, 5, 6, 7, 8}

discard() ---- 移除元素 ,如果元素不存在不做任何操作

三、元组(tuple)

元组的特点:有序的 可以通过下标去获取元素,但是不能去修改元素

创建元组的方法:

1. t = (1,2,3,4)

2. t = tuple()

通过下标获取元素 t[0]

特点: 有序的、元组是一个不可变类型(元组的元素一旦确定下来是不可变的)-------- 能用元组的情况下尽 量不要用列表,因为元组相对于安全

常见方法: ['count', 'index']

注意:元组是不可变的(指向不可变),但是元组中的元素可以是可变

>>> tt = (1,2,3,[1,2,3])
>>> type(tt)
<class 'tuple'>
>>> tt[3][1] = 4
>>> tt
(1, 2, 3, [1, 4, 3])

四、字典(dict)

键值对(key-value)存储值(两列多行的二维表) 创建方法: 1. d = {"name":"zhangsan","age":18} 2. d = dict() 如何访问字典中的值: 通过key去访问value d["name"],如果没有这个value抛出异常 通过key修改value的值 通过key添加键值对(新key =新值 )

>>> d["name"]
'zhangsan'
>>> d["age"] = 20
>>> d
{'name': 'zhangsan', 'age': 20}
>>> d["gender"] = "男"
>>> d
{'name': 'zhangsan', 'age': 20, 'gender': '男'}

常见的方法: ['clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'] clear copy get(key) ----- 通过Key获取value,如果没有key的话不会做任何操作,其实返回的None keys()---- 返回所有的键(key) values() ----- 返回所有的值value items() ----- 返回所有的键值对

>>> d
{'name': 'zhangsan', 'age': 20, 'gender': '男'}
>>> d.keys()
dict_keys(['name', 'age', 'gender'])
>>> d.items()
dict_items([('name', 'zhangsan'), ('age', 20), ('gender', '男')])
>>> d.values()
dict_values(['zhangsan', 20, '男'])

setdefault() ----- 设置默认值

>>> d
{'name': 'zhangsan', 'age': 20, 'gender': '男'}
>>> d.setdefault("name")
'zhangsan'
>>> d.setdefault("password")
>>> d
{'name': 'zhangsan', 'age': 20, 'gender': '男', 'password': None}
>>> d.setdefault("password")

pop(key) ---- 通过key去移除键值对,如果没有这个key会抛出异常

>>> d
{'name': 'zhangsan', 'age': 20, 'gender': '男', 'password': None}
>>> d.pop("gender")
'男'
>>> d
{'name': 'zhangsan', 'age': 20, 'password': None}
>>> d.pop("gender")
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
KeyError: 'gender'

popitem() ----- 移除键值对,根据后进先出的顺序进行删除

>>> help(d.popitem)
Help on built-in function popitem:
popitem() method of builtins.dict instance
    Remove and return a (key, value) pair as a 2-tuple.

    Pairs are returned in LIFO (last-in, first-out) order.
    Raises KeyError if the dict is empty.
>>> d
{'name': 'zhangsan', 'age': 20, 'password': None}
>>> d.popitem()
('password', None)

如何遍历字典?

>>> d
{'name': 'zhangsan', 'age': 20}
>>> for k in d:
...     print(k,d.get(k))
...
name zhangsan
age 20
>>> for k in d.keys():
...     print(k,d[k])
...
name zhangsan
age 20
>>> for k,v in d.items():
...     print(k,v)
...
name zhangsan
age 20

五、字符串

什么是字符串? ----- 由很多有效字符组成串

定义方法: 双引号 单引号 三双引号 三单引号

s = str()

常见的方法: [ 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

capitalize() ---- 格式化字符串的方法 将字符串的首字母转换为大写

center(width, fillchar=' ') ---- 这是字符串长度居中

count() ---- 统计字符或者字符串出现的次数

>>> s
'hahahaha'
>>> s.capitalize()
'Hahahaha'
>>> help(s.center)
Help on built-in function center:
center(width, fillchar=' ', /) method of builtins.str instance
    Return a centered string of length width.
    Padding is done using the specified fill character (default is a space).
>>> s.center(30)
' hahahaha '
>>> s.center(30,"*")
'***********hahahaha***********'
>>> s
'hahahaha'
>>> s.count("h")
4
>>> s.count("ha")
4
>>> s.count("haha")
2

endswith() ---- 判断字符串是不是以XXX结尾

startswith() ---- 判断字符串是不是以XXX开头

index() ---- 查询字符或者字符串在字符串中出现的第一次的位置,如果没有则抛出异常

rindex() ----从右往左找

find() -------- 查询字符或者字符串在字符串中出现的第一次的位置,如果没有则会返回-1

rfind() ------从右往左找

encode() ----将字符串转换为字节数据的方法

如果要将字节数据转换为字符数据用decode()(这个方法是 字节里面的方法 )

>>> s.encode()
b'hahahaha'
>>> d = s.encode()
>>> d
b'hahahaha'
>>> type(d)
<class 'bytes'>
>>> d.decode()
'hahahaha'
>>> ss = d.decode()
>>> type(ss)
<class 'str'>

format() ----- 格式化字符串 a = 3 b =2 print("a = {} ,b ={}".format(a,b))

islower() ------ 判断字母是否全为小写

isupper()------ 判断字母是否全为大写

istitle() ---- 判断是否为标题

isspace() --- 判断是否为空格位

isdigit() ---- 判断是否为数字

isalnum() ----- 不是判断是否位数字,判断是否为有效字符(数字、字母、下划线)

isalpha() ---- 是否全为字母

title() ----- 将字符串转换为标题

lower() ----- 将字符全部转换为小写

upper()------- 将字符全部转换为大写

split() ---- 将字符串按照特定的格式进行分割,返回值是一个列表

join() --- 按照特定的符号将一个可迭代对象拼接字符串

strip() ----- 清除字符串两侧空格

lstrip() -------清除字符串左侧空格

rstrip() -------清除字符串右侧空格

replace(old,new) ----- 用新的字符替换旧的字符

ljust() ------- 左对齐

rjust()------ 右对齐

>>> s
'hahahaha'
>>> s.islower()
True
>>> s.isupper()
False
>>> ss = "This is ..."
>>> ss.istitle()
False
>>> ss = "This Is .."
>>> ss.istitle()
True
>>> s
'hahahaha'
>>> s.isdigit()
False
>>> ss = "1234"
>>> ss.isdigit()
True
>>> ss = "$$$$$"
>>> ss.isalnum()
False
>>> s
'hahahaha'
>>> s.isalnum()
True
>>> s.isalpha()
True
>>> ss = "this is a dog"
>>> ss.title()
'This Is A Dog'
>>> s
'hahahaha'
>>> s.upper()
'HAHAHAHA'
>>> ss
'this is a dog'
>>> ss.split(" ")
['this', 'is', 'a', 'dog']
>>> ss
'this is a dog'
>>> ss.split("s")
['thi', ' i', ' a dog']
>>> help(s.join)
Help on built-in function join:
join(iterable, /) method of builtins.str instance
Concatenate any number of strings.
The string whose method is called is inserted in between each given string.
The result is returned as a new string.
Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
>>> ls = ["a","b","c"]
>>> " ".join(ls)
'a b c'
>>> "*".join(ls)
'a*b*c'
>>> ss = " name "
>>> ss.strip()
'name'
>>> s
'hahahaha'
>>> s.replace("h","H")
'HaHaHaHa'
>>> s
'hahahaha'
>>> s.ljust(30)
'hahahaha '
>>> s.rjust(30)
' hahahaha'
>>> s.rjust(30,"*")
'**********************hahahaha'

六、常见排序

6.1 选择排序

找最小值

arr = [8,3,2,6,1,4,9,7]
    for i in range(0,len(arr)): # 0, 8
        for j in range(i+1,len(arr)):
            if arr[i] >= arr[j]:
                arr[i],arr[j] = arr[j],arr[i]
print(arr)

6.2 冒泡排序

找最大值

arr = [8,3,2,6,1,4,9,7]
    for i in range(0,len(arr)-1): # 0, 7
        for j in range(0,len(arr)-1-i):
            if arr[j] >= arr[j+1]:
               arr[j],arr[j+1] = arr[j+1],arr[j]
print(arr)

6.3 插入排序

arr = [8,3,2,6,1,4,9,7]
for i in range(0,len(arr)):
    for j in range(i,0,-1):
        if arr[j] <= arr[j-1]:
            arr[j],arr[j-1] = arr[j-1],arr[j]
print(arr)

6.4 计数排序(桶排序)

# arr = [8,3,2,6,1,4,9,7]
arr = [7,3,2,0,1,2,3,6]
max_num = arr[0]
min_num = arr[0]
for num in arr:
    if num > max_num:
        max_num = num
    elif num < min_num:
        min_num = num
#print(max_num,min_num)
#偏移量
offest = min_num
#计算新列表的长度
len_arr1 = max_num - min_num + 1
#计数列表 ---- 初始化元素全为0
arr1 = [0] * len_arr1
# print(arr1)
#排序后的列表
arr2 = [0] * len_arr1
#计数
for num in arr:
#print(num)
    arr1[num - offest] += 1
print(arr1)
index = 0
for i in range(0,len_arr1):
    for j in range(0,arr1[i]):
        print(i+offest,end="")
        arr2[index] = i + offest
        index += 1
print()
print(arr2)

七、切片操作

切片的作用是在python中是用来切割可迭代对象(容器),一个完整的切片是包含三个参数的:

object[start:end:step]

和range函数相似(参数个数和取值范围) step:步长,默认取值是1,可以为负数,默认方向是从左往右,负数代表从右往左

object[start:] :从start切割到结束位置(为最末端)包含最末端,方向是从左往右

object[start:end] :从start切割到end结束,不包含end(前闭后开),方向是从左往右

object[start:end:step]: 以step为单位从start切割到end结束不包含end(前闭后开),step为正数
的时候方向是从左往右,step为负数的时候方向是从右往左

示例演示:

a = [0,1,2,3,4,5,6,7,8,9]

1,切割获取单个值

>>> a[0]
0
>>> a[-4]
6

2,切割完整对象

>>> a[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[::]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[::-1]#-1 从右往左
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

3,start和end全为正数的情况下

>>> a[1:6]
[1, 2, 3, 4, 5]
>>> a[1:6:-1] # start = 1 end = 6 表示从左往右 step=-1 表示的是从右往左 所以自相矛盾 返
回的是空
[]
>>> a[:6]
[0, 1, 2, 3, 4, 5]
>>> a[6:]
[6, 7, 8, 9]
>>> a[6::-1]
[6, 5, 4, 3, 2, 1, 0]

4,start和end全为负数的情况下

>>> a[-1:-6]
[]
>>> a[-1:-6:-1]
[9, 8, 7, 6, 5]
>>> a[:-6]
[0, 1, 2, 3]
>>> a[-6:-1]
[4, 5, 6, 7, 8]
>>> a[-6:]
[4, 5, 6, 7, 8, 9]
>>> a[-6::-1]
[4, 3, 2, 1, 0]

5,start和end分别为正数和负数的情况下

>>> a = [0,1,2,3,4,5,6,7,8,9]
>>> a[1:-6]
[1, 2, 3]
>>> a[-1:-6]
[]
>>> a[1:-6:-1]
[]
>>> a[-1:6]
[]
>>> a[-1:6:-1]
[9, 8, 7]

6,连续切片操作

>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[:8][2:5][-1:]
[4]
a[:8]---- [0 1 2 3 4 5 6 7]---[2:5] ---[2,3,4]--[-1:]---[4]

7,其他对象的切片操作

>>> t = (1,2,3,4)
>>> t[1:3]
(2, 3)
>>> s = "ABCDEFG"
>>> s[1:3]
'BC'
>>> for i in range(1,100)[2::3][-10:]:
... print(i)
...
72
75
78
81
8487
90
93
96
99

8,切片的三个参数表达式

>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[2+1:3*2:7%3] #a[3:6:1]
[3, 4, 5]

注意:

1. 如果进行切片操作的时候,超越下标的话不会报错

2. 如果进行切片操作的时候,参数的取值相互矛盾的话不会报错,会返回一个空列表

3. 在python中实现反向列表输出的方法

循环 list.reverse() 切片[::-1]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Smiling Mr. Rui

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值