列表
列表生成式
import random #引入随机数 lst=[item for item in range(1,11)] print(lst) print() lst2=[item*item for item in range(1,11)] print(lst2) print() lst3=[random.randint(1,100) for item in range(10)]#随机产生数 print(lst3) print() lst4=[i for i in range(1,20) if i%2==0] #可以适当的选择元素建立列表 print(lst4)
代码结果:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[75, 5, 92, 1, 11, 38, 63, 85, 75, 76]
[2, 4, 6, 8, 10, 12, 14, 16, 18]
列表创建和删除
代码演示:
lst=["hellow","world",98,100.5] print(lst) lst2=list("hellow") lst3=list(range(1,10,2)) #从一开始,到10结束,步长为2 print(lst2) print(lst3) #列表是序列的一种,对序列有用的操作符,运算符,函数也有 print(lst+lst2+lst3) #内容连接 print(lst*3) #内容翻倍 print(len(lst)) #列表中元素的个数 print(max(lst3)) #列表中最大 print(min(lst3)) print() print(lst2.count("o"))#统计在列表中o出现的次数 print(lst2.index("h"))#查询h在列表出现的下标 print() lst4=[10,12,111] print(lst4) del lst4 #到这一步删除,所有前面还是会显示 #print(lst4) 该处会报错,lst4已经删除
代码结果
['hellow', 'world', 98, 100.5]
['h', 'e', 'l', 'l', 'o', 'w']
[1, 3, 5, 7, 9]
['hellow', 'world', 98, 100.5, 'h', 'e', 'l', 'l', 'o', 'w', 1, 3, 5, 7, 9]
['hellow', 'world', 98, 100.5, 'hellow', 'world', 98, 100.5, 'hellow', 'world', 98, 100.5]
4
9
1
1
0
[10, 12, 111]
列表的相关操作
lst=["hellow","world","python",100] print("原列表:",lst,id(lst)) #增加元素 lst.append("C语言") print("增加后的列表:",lst,id(lst)) print() #使用insert函数从指定位置插入元素 lst.insert(1,101) #插入特定位置以及元素 1为下标位置,101为你要加入的元素 print("插入后的列表:",lst,id(lst)) print() #删除元素 lst.remove("C语言") print("删除后的列表:",lst,id(lst)) print() #也是删除元素,但是是先将元素移出,后删除 print(lst.pop(1))#1为索引,该列表中的元素是101 print(lst) print() #清空列表 # lst.clear() # print(lst,id(lst)) #列表的反向输出 lst.reverse() print(lst) print() #列表的拷贝 new_lst=lst.copy() print(lst,id(lst)) print(new_lst,id(new_lst)) print() #列表的修改,直接通过索引去修改 lst[1]="happy" print(lst,id(lst))
代码结果
原列表: ['hellow', 'world', 'python', 100] 2575347714496
增加后的列表: ['hellow', 'world', 'python', 100, 'C语言'] 2575347714496
插入后的列表: ['hellow', 101, 'world', 'python', 100, 'C语言'] 2575347714496
删除后的列表: ['hellow', 101, 'world', 'python', 100] 2575347714496
101
['hellow', 'world', 'python', 100]
[100, 'python', 'world', 'hellow']
[100, 'python', 'world', 'hellow'] 2575347714496
[100, 'python', 'world', 'hellow'] 2575348624384
[100, 'happy', 'world', 'hellow'] 2575347714496
列表的遍历操作
代码
#三种方式 #第一种使用for循环 lst=["hellow","world",98,45,"boy"] for item in lst: print(item) print() #第二种,使用for循环,len(),range()函数 for i in range(0,len(lst)): print(i,"----->",lst[i]) print() #第三种,使用enumerate for index,item in enumerate(lst): print(index,item) #index是序号不是索引,index是可以手动修改的,index和item都是自己定义的 print() for index,item in enumerate(lst,start=1): #可以让序号从一开始 print(index,item) print() for index, item in enumerate(lst, 1): # 可以省略start print(index, item)
代码结果
hellow
world
98
45
boy
0 -----> hellow
1 -----> world
2 -----> 98
3 -----> 45
4 -----> boy
0 hellow
1 world
2 98
3 45
4 boy
1 hellow
2 world
3 98
4 45
5 boy
1 hellow
2 world
3 98
4 45
5 boy
列表的排序操作
代码:
lst=[65,45,10,20,14,100,12] print("原列表:",lst) print() #列表的排序,默认为升序(reverse=False) lst.sort() print("排完序的列表为:",lst) #降序 lst.sort(reverse=True) print("排完序的列表为:",lst) print() print("~~~~"*8) #英文单词也可以排序,按照ASCLL值,所以升序先排大写再排小写 lst2=["banana","apple","pear","Cat"] lst2.sort() print("排完升序的列表为:",lst2) #降序同上 lst2.sort(reverse=True) print("排完降序的列表为:",lst2) print() #忽略大小写进行比较 lst2.sort(key=str.lower)#将其全部转换为小写进行排序,但是不会导致输出内容的改变 print(lst2)
代码结果:
原列表: [65, 45, 10, 20, 14, 100, 12]
排完序的列表为: [10, 12, 14, 20, 45, 65, 100]
排完序的列表为: [100, 65, 45, 20, 14, 12, 10]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
排完升序的列表为: ['Cat', 'apple', 'banana', 'pear']
排完降序的列表为: ['pear', 'banana', 'apple', 'Cat']
['apple', 'banana', 'Cat', 'pear']
sorted()内置函数的使用
代码
lst=[65,45,10,20,14,100,12] print("原列表:",lst) new_lst=sorted(lst)#会产生一个新的列表,默认升序 print("升序:",new_lst) print("原列表:",lst) new_lst2=sorted(lst,reverse=True)#降序 print("降序:",new_lst2) print("原列表:",lst) print() lst2=["banana","apple","pear","Cat"] print("原列表:",lst2) new_lst3=sorted(lst2,key=str.lower)#忽略大小写排序 print("升序:",new_lst3)
代码结果
原列表: [65, 45, 10, 20, 14, 100, 12]
升序: [10, 12, 14, 20, 45, 65, 100]
原列表: [65, 45, 10, 20, 14, 100, 12]
降序: [100, 65, 45, 20, 14, 12, 10]
原列表: [65, 45, 10, 20, 14, 100, 12]
原列表: ['banana', 'apple', 'pear', 'Cat']
升序: ['apple', 'banana', 'Cat', 'pear']
二维列表的遍历和生成式
代码
lst=[ ["城市","环比","同比"], ["北京",145,171], ["上海",147,178], ["重庆",145,100] ] print(lst) #遍历二维列表用双层fou循环 for row in lst: for item in row: print(item,end="\t") print() #列表生成式生成一个4行5列的列表 lst2=[[j for j in range(5)]for i in range(4)] print(lst2)
代码结果:
[['城市', '环比', '同比'], ['北京', 145, 171], ['上海', 147, 178], ['重庆', 145, 100]]
城市 环比 同比
北京 145 171
上海 147 178
重庆 145 100
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
元组
元组的生成式
代码
t=(i for i in range(1,4)) print(t) #直接显示看不见内容 t=tuple(t) #将其转换为元组 print(t) #遍历 for item in t: print(item) #两个遍历操作不能联用,遍历过程将元素取出来 y=(i for i in range(1,5)) print(y) print(y.__next__()) print(y.__next__()) print(y.__next__()) print(y.__next__()) y=tuple(y) print(y)
代码结果
<generator object <genexpr> at 0x00000205CBDC5B10>
(1, 2, 3)
1
2
3
<generator object <genexpr> at 0x00000205CBDC4380>
1
2
3
4
()
元组的创建和删除
代码
#用小括号直接创建元组 t=(66,[123,12,45],"ddd") print(t) print() #用tuple函数创建元组 t=tuple("helloword") print(t) print() t=tuple([123,12,45,45,45]) print(t) print("该元组是否有12:",12 in t) print("该元组没有12:",12 not in t) #如果元组只有一个元素 t=(10) print(type(t)) ##如果元组只有一个元素,逗号不能省 t=(10,) print(type(t)) #删除元组,和列表的操作一样 del t #如果输出会报错
代码结果
(66, [123, 12, 45], 'ddd')
('h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'd')
(123, 12, 45, 45, 45)
该元组是否有12: True
该元组没有12: False
<class 'int'>
<class 'tuple'>
元组元素的遍历
代码
t=("hellow","ok","world") #根据索引访问元组 print(t[0]) #也可以进行切片操作 t2=t[0:3:2] print(t2) print() #元组的遍历,第一种 for item in t: print(item) print() #元组的遍历,第二种 for i in range(len(t)): print(i,t[i]) print() #元组的遍历,第三种 for index,item in enumerate(t): print(index,"----->",item) print() #可以控制开始的值 for index,item in enumerate(t,start=1): print(index,"----->",item)
代码结果
hellow
('hellow', 'world')
hellow
ok
world
0 hellow
1 ok
2 world
0 -----> hellow
1 -----> ok
2 -----> world
1 -----> hellow
2 -----> ok
3 -----> world
集合
集合的创建和删除
代码
s={10,20,10,12} print(s) #集合只能存储不可变数据类型,像列表和字典是可变数据类型,存储会报错 print() #使用set()创建集合 s=set()#创建一个空集合 print(s) s={} #为字典 print(s,type(s)) print() s=set("hellowwold") #其中元素显示而且不会重复 print(s) s2=set([10,20,30])#将列表强制类型转换为元组 print(s2) s3=set(range(1,10)) print(s3) #集合也是序列的一种 print(max(s3)) print(min(s3)) print(len(s3)) print("9在s3中存在吗:",9 in s3) print("8在s3中不存在吗:",8 not in s3) #集合的删除和前面一样del,不能在输出会报错 del s3
代码结果
{10, 20, 12}
set()
{} <class 'dict'>
{'h', 'l', 'w', 'd', 'o', 'e'}
{10, 20, 30}
{1, 2, 3, 4, 5, 6, 7, 8, 9}
9
1
9
9在s3中存在吗: True
8在s3中不存在吗: False
集合的相关操作,遍历及生成式
代码:
s={10,20,30} #添加元素 s.add(100) print(s) #删除元素 s.remove(10) print(s) #清空元素 # s.clear() # print(s) print() #集合的遍历操作 for item in s: print(item) #第二种使用enumerate函数 for index,item in enumerate(s,start=1): #默认从0开始 print(index,"---->",item) print() #集合生成式 s={i for i in range(10)} print(s) s={i for i in range(10)if i%2==1} print(s)
代码结果
{100, 10, 20, 30}
{100, 20, 30}
100
20
30
1 ----> 100
2 ----> 20
3 ----> 30
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
{1, 3, 5, 7, 9}
集合的操作符
代码
A={10,20,45,30,40,99} B={10,45,88,77,55,23} #交集 print(A&B) #并集 print(A|B) #差集 print(A-B) #补集,对称差 print(A^B)
代码结果
{10, 45}
{99, 40, 10, 45, 77, 20, 23, 55, 88, 30}
{40, 99, 20, 30}
{77, 20, 23, 88, 30, 99, 40, 55}
字典
字典生成式
import random #第一种 d={item:random.randint(1,100) for item in range(4)} print(d) print() #第二种映射的方式 lst=[100,111,121,145] lst2=["王晓霞","李简易","陈汽车","任取余"] d={key:value for key,value in zip(lst,lst2)} print(d) #{100: '王晓霞', 111: '李简易', 121: '陈汽车', 145: '任取余'}
代码结果
{0: 4, 1: 99, 2: 20, 3: 9}
{100: '王晓霞', 111: '李简易', 121: '陈汽车', 145: '任取余'}
字典的创建和删除
代码
#直接创建字典 d={10:"cat",20:"dog",30:"bird",20:"car"} #当键一样时,后面的值会覆盖前面的值 print(d) print() #zip函数 lst=[10,20,30,40] lst2=["car","cat","dog","bird","child"] #多余数据不会对应显示 zipobj=zip(lst,lst2) print(zipobj) #<zip object at 0x00000163BC0E6D00> print() # d=list(zipobj) #将其转换为列表类型 # print(d) #[(10, 'car'), (20, 'cat'), (30, 'dog'), (40, 'bird')] 显示为列表类型 d=dict(zipobj) print(d) #{10: 'car', 20: 'cat', 30: 'dog', 40: 'bird'} #显示为字典类型 print() #使用参数创建字典 d=dict(cat=10,dog=20,bird=30) #左边是键key,右边是值value print(d) print() #元组可以作为键,而列表不可以(会报错) 不可变数据类型可以作键,而列表为可变数据类型 t=(1,2,3) print({t:"123"}) #字典属于序列 {'cat': 10, 'dog': 20, 'bird': 30} print(max(d)) print(min(d)) print(len(d)) del d #为删除
代码结果
{10: 'cat', 20: 'car', 30: 'bird'}
<zip object at 0x0000019F86526DC0>
{10: 'car', 20: 'cat', 30: 'dog', 40: 'bird'}
{'cat': 10, 'dog': 20, 'bird': 30}
{(1, 2, 3): '123'}
dog
bird
3
字典的相关操作和方法
代码
d={"hellow":10,"world":20,"python":30} print(d) #向字典中添加元素 d["bird"]=40 print(d) #直接进行赋值 print() #获取字典中所有的键 keys=d.keys() print(keys)#dict_keys(['hellow', 'world', 'python', 'bird']) print(list(keys))#转换为列表的类型 print(tuple(keys))#转换为元组的类型 print() #获取字典中所有的值 values=d.values() print(values) print(list(values)) print(tuple(values)) print() #将字典中的数据的形式转成键值对的形式,以元组的方式输出 lst=list(d.items()) print(lst) #[('hellow', 10), ('world', 20), ('python', 30), ('bird', 40)] d=dict(lst) print(d) #{'hellow': 10, 'world': 20, 'python': 30, 'bird': 40} print() #pop函数 print(d.pop("hellow"))#10 print(d) #{'world': 20, 'python': 30, 'bird': 40} 先取出后删除 print(d.pop(10086,"不存在"))#与查询key的d.get相似 不存在 print() #随机删除 print(d.popitem()) print(d) #清空字典里的所有元素 d.clear() print(d) #{} print(bool(d)) #空字典的布尔值为False
代码结果
{'hellow': 10, 'world': 20, 'python': 30}
{'hellow': 10, 'world': 20, 'python': 30, 'bird': 40}
dict_keys(['hellow', 'world', 'python', 'bird'])
['hellow', 'world', 'python', 'bird']
('hellow', 'world', 'python', 'bird')
dict_values([10, 20, 30, 40])
[10, 20, 30, 40]
(10, 20, 30, 40)
[('hellow', 10), ('world', 20), ('python', 30), ('bird', 40)]
{'hellow': 10, 'world': 20, 'python': 30, 'bird': 40}
10
{'world': 20, 'python': 30, 'bird': 40}
不存在
('bird', 40)
{'world': 20, 'python': 30}
{}
False
字典元素的访问和遍历
代码
d={"hellow":10,"world":20,"python":30} #访问字典中的元素 #使用d[key] print(d["hellow"]) #输出对应的值 #使用d.get print(d.get("hellow")) #输出对应的值 #这两者存在着区别,如果元素不存在d[key]会报错,而d.get会输出默认值none(也可以指定) print(d.get("java")) #None print(d.get("java","不存在"))#不存在 可以指定输出 print() #字典的遍历 for item in d.items(): print(item) #以元组的形式输出 print() #使用for循环分别遍历key,value for key,value in d.items(): print(key,"------>",value)
代码结果
10
10
None
不存在
('hellow', 10)
('world', 20)
('python', 30)
hellow ------> 10
world ------> 20
python ------> 30
字典合并和同步迭代
代码
dict1={"a":10,"b":20} dict2={"c":30,"d":40} merge_dict=dict1|dict2 #使用|即可合并 print(merge_dict) print() #同步迭代 fruits=["apple","pear","grape"] count=[10,20,30] for f,c in zip(fruits,count): match f,c: case "apple",10: print("10个苹果") case "pear", 20: print("20个梨") case "grape", 30: print("30个葡萄")
代码结果
{'a': 10, 'b': 20, 'c': 30, 'd': 40}
10个苹果
20个梨
30个葡萄
序列切片操作
代码
#s[开始:结束:步长] s="hellowWord" s1=s[0:5:2] #索引从0开始,到5结束,但是吧包含5,步长为2 print(s1) print(s[:5:1]) #开始位置默认为0 print(s[:5:]) #步长默认为1 print(s[0::])#结束默认到最后一个元素 print(s[5::])#不写为默认 print(s[5:])#一个冒号,不写也为默认 print(s[-1:-10:-1])#逆序输出,注意步长也也要设置为负数
代码结果
hlo
hello
hello
hellowWord
wWord
wWord
droWwolle