python3-学习笔记--列表(list),元组(tuple),字典(dict),集合(set)

本文详细介绍了Python中的四种基本数据结构:列表、元组、字典和集合的基本操作、特性和应用场景,适合Python初学者和进阶者阅读。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

目录

 

 

一,list

 

(一),声明方式

(二),访问列表

(三),更新列表

(四),删除列表元素

(五),Python列表脚本操作符

(六),嵌套列表

(七),Python列表函数&方法

二,元组

(一),声明

(二),修改元组

(三),删除元组

(四):运算符,索引,截取,跟list一样

(五),list 与元组 相互转化

三,字典

(一),字典声明

(二),修改字典

     (三),删除字典元素

  (四),字典内置函数&方法

(五),字典包含了以下内置方法

四,集合

 (一),声明

 (二),添加元素

(三),移除元素,清空集合,其他函数

 


 

一,list

 

(一),声明方式

list1 = ['Google', 'Runoob', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"];

(二),访问列表

与字符串的索引一样,列表索引从0开始。列表可以进行截取、组合等。

两者不一样的是,获取的类型不一样,截取的是list类型,而下标获取的是数据原本的类型

print(list1[2]);
print(list1[2:4]);

 

(三),更新列表

           可以忽视类型直接根据下标更新

print ("第三个元素为 : ", list1[1]);
list1[1] = 2001;
print ("更新后的第三个元素为 : ", list1[1]);

console:
第三个元素为 :  Runoob
更新后的第三个元素为 :  2001

(四),删除列表元素

print ("原始列表 : ",list1, str(list1),"长度",len(list1));
del list1[2]
print ("删除第三个元素 : ", list1, str(list1),"长度",len(list1));

console:
原始列表 :  ['Google', 'Runoob', 1997, 2000] ['Google', 'Runoob', 1997, 2000] 长度 4
删除第三个元素 :  ['Google', 'Runoob', 2000] ['Google', 'Runoob', 2000] 长度 3

(五),Python列表脚本操作符

print("列表长度 : len()",len(list1));
list=list1+list2;
print("列表拼接 : list1 + list2",list);
print("列表重复 : list1 * 2",list1*2);
print("列表包含 : 2000 in list1", 2000 in list1);
print("列表迭代 : ", end="");
for x in list1: print(x, end=" ");

console:
列表长度 : len() 4
列表拼接 : list1 + list2 ['Google', 'Runoob', 1997, 2000, 1, 2, 3, 4, 5]
列表重复 : list1 * 2 ['Google', 'Runoob', 1997, 2000, 'Google', 'Runoob', 1997, 2000]
列表包含 : 2000 in list1 True
列表迭代 : Google Runoob 1997 2000 

(六),嵌套列表

这个很熟悉有木有,跟JAVA多维数组的一样

list=[['a', 'b', 'c'], [1, 2, 3]];
# for x in list: print(x, end=" ");
print(list[0][1])

 

(七),Python列表函数&方法

len(list) 列表元素个数
max(list) 返回列表元素最大值
min(list) 返回列表元素最小值
list(seq) 将元组转换为列表

max  min  只能用于数据为同类型的列表
嵌套列表也可以使用,单返回的拥有最大值或最小值的子列表
list=[[1, 5, 1], [1, 2, 3],[1,2,4]];
print(max(list));print(min(list));
console:
[1, 5, 1]
[1, 2, 3]

 

print('列表末尾添加新的元素',end=" ");
for x in list1:print(x,end=" ");
list1.append('Google');
for x in list1:print(x,end=" ");
print();print("统计元素出现的次数 ",list1.count('Google'))
list2.extend(list3);print("列表末尾追加另一个序列",end=" ");
for x in list2:print(x,end=" ");
print();print("找到列表中某个元素的索引",list1.index(1997));
list1.insert(3,1998);
for x in list1:print(x,end=" ");
print();print("移除列表中的一个元素(默认最后一个元素),并且返回该元素的值",list1.pop(-3));
for x in list1:print(x,end=" ");
print();print("移除列表中某个值的第一个匹配项",list1.remove('Google'));
for x in list1:print(x,end=" ");
# 没有报错  ValueError: list.remove(x): x not in list  有了返回None
print();print("反向列表中元素",list1.reverse());
for x in list1:print(x,end=" ");
print();print("复制列表");list4=	list1.copy();
for x in list4:print(x,end=" ");
print();print("clear() 函数用于清空列表,类似于 del a[:]",list1.clear());
for x in list1:print(x,end=" ");print();

console:
列表末尾添加新的元素 Google Runoob 1997 2000 Google Runoob 1997 2000 Google 
统计元素出现的次数  2
列表末尾追加另一个序列 1 2 3 4 5 a b c d 
找到列表中某个元素的索引 2
Google Runoob 1997 1998 2000 Google 
移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 1998
Google Runoob 1997 2000 Google 
移除列表中某个值的第一个匹配项 None
Runoob 1997 2000 Google 
反向列表中元素 None
Google 2000 1997 Runoob 
复制列表
Google 2000 1997 Runoob 
clear() 函数用于清空列表,类似于 del a[:] None

 

排序

# list.sort(cmp=None, key=None, reverse=False)
# 对原列表进行排序
# cmp - - 可选参数, 如果指定了该参数会使用该参数的方法进行排序。
# key - - 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
# reverse - - 排序规则,reverse = True降序, reverse = False,升序(默认)。
list2.sort(reverse = 1);print ( '降序输出:', list2 );
list2.sort();print ( '升序序输出:', list2 );

console:
降序输出: [5, 4, 3, 2, 1]
降序输出: [1, 2, 3, 4, 5]

二,元组

(一),声明

Python 的元组与列表类似,不同之处在于元组的元素不能修改。

元组使用小括号,列表使用方括号。

元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。


tuple = ();#空元组

#元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被当作运算符使用:

t=(1);t1=(1,);print(type(t),"   ",type(t1));
console:
<class 'int'>     <class 'tuple'>


tuple1 = ('Google', 'Runoob', 1997, 2000)
tuple2 = (1, 2, 3, 4, 5, 6, 7)
tuple3 = "a", "b", "c", "d";   #  不需要括号也可以

print ("tuple1[0]: ", tuple1[0])
print ("tuple2[1:5]: ", tuple2[1:5])
print ("tuple3[1:]: ", tuple3[1:]);
for x in tuple3:print(x,end="  ");
console:
tuple1[0]:  Google
tuple2[1:5]:  (2, 3, 4, 5)
tuple3[1:]:  ('b', 'c', 'd')
a  b  c  d  

(二),修改元组

          元组中的元素值是不允许修改的,但我们可以对元组进行连接组合,如下实例:

tuple1 = ('Google', 'Runoob', 1997, 2000);
tuple2 = (1, 2, 3, 4, 5, 6, 7) ;
print("tup1[0]: ", tuple1[0]);
print("tup2[1:5]: ", tuple2[1:5]) 
 
tuple3=tuple1+tuple2;print(tuple3);#以拼接的方式,创建一个新的元组

(三),删除元组

     元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组

print(tuple1);
# del tuple1[0];#TypeError: 'tuple' object doesn't support item deletion
del tuple1;print(tuple1);#name 'tuple1' is not defined
console:
('Google', 'Runoob', 1997, 2000)

 

(四):运算符,索引,截取,跟list一样

print(tuple4,type(tuple4));
print("元组长度",len(tuple4));
print("元组最大值",max(tuple4));
print("元组最小值",min(tuple4));
print("元组无法改变,所以没有排序,但是可以转换成list排序之后再转换回来");
tuple=tuple4+tuple4;
print("元组拼接 : tuple4 + tuple4",tuple);
print("元组重复 : tuple4 * 2",tuple4*2);
print("元组包含 : 2 in tuple4", 2 in tuple4);
print("元组迭代 : ", end="");
for x in tuple4: print(x, end=" ");
console:
(2, 0, 1, 8) <class 'tuple'>
元组长度 4
元组最大值 8
元组最小值 0
元组无法改变,所以没有排序,但是可以转换成list排序之后再转换回来
元组拼接 : tuple4 + tuple4 (2, 0, 1, 8, 2, 0, 1, 8)
元组重复 : tuple4 * 2 (2, 0, 1, 8, 2, 0, 1, 8)
元组包含 : 2 in tuple4 True
元组迭代 : 2 0 1 8 

(五),list 与元组 相互转化

list1=list(tuple3);print(list1,type(list1));
tuple=tuple(list1);print(tuple,type(tuple));
console:
['a', 'b', 'c', 'd'] <class 'list'>
('a', 'b', 'c', 'd') <class 'tuple'>

三,字典

(一),字典声明

字典是另一种可变容器模型,且可存储任意类型对象。
           字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中
           键必须是唯一的,但值则不必。值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。

dict1={1:[1,2,3],"2":(3,4,5),():"空元组",(1,):"元组",(1):"true",True:"True",False:"FALSE"};

print("",type(dict1));
print(dict1);print(dict1[True]);
console:
<class 'dict'>
{1: 'True', '2': (3, 4, 5), (): '空元组', (1,): '元组', False: 'FALSE'}
True

这让我想起了MAP,但是经过测试我发现有趣的出现了,True代表1,False代表0.而且,字典的键并不是不能重复,而是会被覆盖,被后面的声明覆盖.。字典的键认为,  1   ,True ,(1)  是一个。此外,单引号,双引号,三引号声明的KET也是一样。

(二),修改字典

dict2={"pycharm":"pycharm",3:3,(3,):[2018]};
print(dict2)
dict2[3]=4;print("修改",dict2);
dict2[1]=4;print("新增",dict2);
console:
{'pycharm': 'pycharm', 3: 3, (3,): [2018]}
{'pycharm': 'pycharm', 3: 4, (3,): [2018]}
{'pycharm': 'pycharm', 3: 4, (3,): [2018], 1: 4}

这里有个深深的疑问?修改的时候,是不是在末尾添加一条数据,只是因为覆盖没有显示出来。会不会效率低下。

     (三),删除字典元素

del dict2[3];print(dict2)      # 删除键 3
dict2.clear() ;print(dict2)    # 清空字典
del dict2   ;print(dict2)      # 删除字典 这会引发一个异常,因为用执行 del 操作后字典不再存在
console:
{'pycharm': 'pycharm', (3,): [2018]}
{}
NameError: name 'dict2' is not defined

 

  (四),字典内置函数&方法

print("dict2的长度",len(dict2));
print("dict2转化str",str(dict2));
print("dict2类型",type(dict2),isinstance(dict2,dict));
console:
dict2的长度 3
dict2转化str {'pycharm': 'pycharm', 3: 3, (3,): [2018]}
dict2类型 <class 'dict'> True

(五),字典包含了以下内置方法

                 1,dict.clear()   删除字典内所有元素

dict1={1:"a",2:"b",3:"c"};
dict2=dict1.copy();
print(str(dict1));#{1: 'a', 2: 'b', 3: 'c'}
print("删除字典内所有元素: dict.clear",end=" ");
dict1.clear();print(str(dict1));#删除字典内所有元素: dict.clear {}
console:
{1: 'a', 2: 'b', 3: 'c'}
删除字典内所有元素: dict.clear {}

    2,dict.copy()   函数返回一个字典的浅复制(直接赋值、浅拷贝和深度拷贝解析 区分)

dict1={1:"a",2:[1,2]};
dict2 = dict1;                 # 赋值引用: 引用对象,都指向同一个对象
dict3=dict1.copy();            # 浅拷贝:深拷贝父对象(一级目录),子对象(二级目录)不拷贝(父对象独立,子对象还是只想同一对象是引用)
import copy;# 导入整个模块
dict4=copy.deepcopy(dict1);    # 深度拷贝:深拷贝父对象(一级目录),子对象(二级目录),两者是完全独立

print("dict1:",dict1,"   dict2:",dict2,"   dict3:",dict3,"   dict4:",dict4);
dict1[1]="c";
print("修改val  dict1:",dict1,"   dict2:",dict2,"   dict3:",dict3,"   dict4:",dict4);
dict1[3]="c";
print("添加val  dict1:",dict1,"   dict2:",dict2,"   dict3:",dict3,"   dict4:",dict4);
dict1[2].remove(2);
print("删除元素val的一部分  dict1:",dict1,"   dict2:",dict2,"   dict3:",dict3,"   dict4:",dict4);
dict1.clear();
print("删除字典内所有元素   dict1:",dict1,"   dict2:",dict2,"   dict3:",dict3,"   dict4:",dict4);

console:
赋值后               dict1: {1: 'a', 2: [1, 2]}            dict2: {1: 'a', 2: [1, 2]}    
                     dict3: {1: 'a', 2: [1, 2]}            dict4: {1: 'a', 2: [1, 2]}
					 
修改val              dict1: {1: 'c', 2: [1, 2]}            dict2: {1: 'c', 2: [1, 2]}    
                     dict3: {1: 'a', 2: [1, 2]}            dict4: {1: 'a', 2: [1, 2]}
					 
添加val              dict1: {1: 'c', 2: [1, 2], 3: 'c'}    dict2: {1: 'c', 2: [1, 2], 3: 'c'}          
                     dict3: {1: 'a', 2: [1, 2]}            dict4: {1: 'a', 2: [1, 2]}
					 
删除元素val的一部分  dict1: {1: 'c', 2: [1], 3: 'c'}       dict2: {1: 'c', 2: [1], 3: 'c'}    
                     dict3: {1: 'a', 2: [1]}               dict4: {1: 'a', 2: [1, 2]}
					 
删除字典内所有元素   dict1: {}                             dict2: {}    
                     dict3: {1: 'a', 2: [1]}               dict4: {1: 'a', 2: [1, 2]}

3,dict.fromkeys(seq[, value]) 创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值

  seq不能是int float bool None ,value不能是 float,bool,None

dict={};
seqlist=[1,2,3,4];
seq = ('name', 'age', 'sex')
str1="1,2,3";
dict = dict.fromkeys(seqlist);#value 默认为None
print ("新的字典(list)为 : %s" %  str(dict))
dict = dict.fromkeys(seq);
print ("新的字典(元组)为 : %s" %  str(dict))
dict = dict.fromkeys(str1);
print ("新的字典(字符串)为 : %s" %  str(dict))
console;
新的字典(list)为 : {1: None, 2: None, 3: None, 4: None}
新的字典(元组)为 : {'name': None, 'age': None, 'sex': None}
新的字典(字符串)为 : {'1': None, ',': None, '2': None, '3': None}


dict1={1:1};
dict = dict.fromkeys(seq, 10)
print ("新的字典为(数字) : %s" %  str(dict))
dict = dict.fromkeys(seqlist, seqlist)
print ("新的字典(list)为 : %s" %  str(dict))
dict = dict.fromkeys(seqlist, seq)
print ("新的字典(元组)为 : %s" %  str(dict))
dict = dict.fromkeys(seqlist, str1)
print ("新的字典(字符串)为 : %s" %  str(dict))
dict = dict.fromkeys(seqlist, dict1)
print ("新的字典(字典)为 : %s" %  str(dict))
console;
新的字典为(数字) : {'name': 10, 'age': 10, 'sex': 10}
新的字典(list)为 : {1: [1, 2, 3, 4], 2: [1, 2, 3, 4], 3: [1, 2, 3, 4], 4: [1, 2, 3, 4]}
新的字典(元组)为 : {1: ('name', 'age', 'sex'), 2: ('name', 'age', 'sex'), 3: ('name', 'age', 'sex'), 4: ('name', 'age', 'sex')}
新的字典(字符串)为 : {1: '1,2,3', 2: '1,2,3', 3: '1,2,3', 4: '1,2,3'}
新的字典(字典)为 : {1: {1: 1}, 2: {1: 1}, 3: {1: 1}, 4: {1: 1}}


        4,dict.get(key, default=None) 和dict.setdefault(key, default=None)

   返回指定键的值,如果值不在字典中返回default值
              区别是后者,如果不在字典中,则插入 key 及设置的默认值 default,并返回 default ,default 默认值为 None。

dict1 = {1: "a", 2: [1, 2]};
print(dict1.get(1,"没有"),dict1.get(3,"没有"),dict1)
print(dict1.setdefault(1, None),dict1.setdefault(3, 3),dict1);#插入到末尾
console:
a 没有 {1: 'a', 2: [1, 2]}
a 3 {1: 'a', 2: [1, 2], 3: 3}

5,key in dict  如果键在字典dict里返回true,否则返回false

 

dict1 = {1: "a", 2: [1, 2]};
print(1 in dict1,3 in dict1)
console:
True False

 

6,dict.items() 以列表返回可遍历的(键, 值) 元组数组

dict1 = {1: "a", 2: [1, 2]};
print ("Value : %s" %  dict1.items())
#遍历字典
for i,j in dict1.items():
    print(i, ":\t", j)
dict2 ={};#赋值字典
for i, j in dict1.items():
    dict2[i]=j;
print(dict2)
console:
Value : dict_items([(1, 'a'), (2, [1, 2])])
1 :	 a
2 :	 [1, 2]
{1: 'a', 2: [1, 2]}

7,dict.keys()dict.values()返回一个迭代器,可以使用 list() 来转换为列表

dict1 = {1: "a", 2: [1, 2]};
print ("Value : %s" %  dict1.items())
list1=dict1.keys();#或得的KTY不是list 类型
print(list1,type(list1));
list2=list(dict1.keys());#需要用list函数转换
print(list2,type(list2));
console:
Value : dict_items([(1, 'a'), (2, [1, 2])])
dict_keys([1, 2]) <class 'dict_keys'>
[1, 2] <class 'list'>


list3=dict1.values();print(list3,type(list3));
list4=list(dict1.values());print(list4,type(list4));
console:
dict_values(['a', [1, 2]]) <class 'dict_values'>
['a', [1, 2]] <class 'list'>

8,dict.update() 函数把字典参数 dict2 的 key/value(键/值) 对更新到字典 dict 里。

dict1 = {1: "a", 2: [1, 2]};
dict2 = {3: "c"};
dict3 = {1: "b"};
print(dict1.update(dict2),dict1);#没有重复就添加
print(dict1.update(dict3),dict1);#有重复的就替换
console:
None {1: 'a', 2: [1, 2], 3: 'c'}
None {1: 'b', 2: [1, 2], 3: 'c'}

         9,dict.pop() 方法删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。

dict1 = {1: "a", 2: [1, 2]};
print(dict1.pop(1),dict1);
print(dict1.pop(3,"没有"),dict1);#没有默认值,必须添加
console:
a {2: [1, 2]}
没有 {2: [1, 2]}

10.dict.popitem() 随机返回并删除字典中的一对键和值(一般删除末尾对)。

dict1 = {1: "a", 2: [1, 2]};
print("删除的元素是 ",dict1.popitem(),"  删除元素后的字典  ",dict1);
console:
删除的元素是  (2, [1, 2])   删除元素后的字典   {1: 'a'}

四,集合

 (一),声明

set1={True,1,"set",(1,2),0,False,1.1};
print(set1);#显示第一个,之后的去重
print("查看某个元素是否在集合内,有返回True,否则False", 1 in set1,10 in set1)
set2=set("str1.1(2,),3,False");print(set2);#字符串,相当于单字符
tuple1=("str",1.1,(2,),3,False);#可以用元组来实现混搭
set3=set(tuple1);print(set3);
console:
{(1, 2), True, 0, 1.1, 'set'}
查看某个元素是否在集合内,有返回True,否则False True False
{'3', 't', 'r', '.', 'F', 'e', '1', ',', 'l', 'a', '(', ')', '2', 's'}
{False, 3, (2,), 1.1, 'str'}


set1=set("1234");
set2=set("3456");
print("集合set1 %s" % set1,"集合set2 %s" % set2);
print("set1去除跟set2重复的  set1 - set2   " , set1 - set2);
print("两个集合所有不重复元素 set1 | set2   " , set1 | set2);
print("交集,都有的 set1 & set2   " , set1 & set2);
print("不同时存在的 set1 ^ set2   " , set1 ^ set2);
console:
集合set1 {'3', '1', '4', '2'} 集合set2 {'3', '6', '4', '5'}
集合set1 - set2    {'1', '2'}
集合set1 | set2    {'3', '4', '1', '6', '5', '2'}
集合set1 & set2    {'3', '4'}
集合set1 ^ set2    {'6', '1', '5', '2'}

 (二),添加元素

set1=set("2018");
print(set1);#显示第一个,之后的去重
set1.add(0);set1.add(False);#只能添加一个,重复添加无效
set1.add(True);set1.add(1);#只保留第一次添加的
print(set1);

#update()更新可以是多个,类型必须一致,且参数可以是列表,元组,字典,字符串
# set1=set();set1.update(1.1,2.2,3.3,4.4);print(set1);
set2=set();set2.update((1,),(2,));print(set2);
set3=set();set3.update([1,2],[3,4]);print(set3);
set4=set();set4.update({1:2},{3:4});print(set4);
# set5=set();set5.update(1,2,3,4);print(set5);
set6=set();set6.update("1","2","3","4");print(set6);
console:
{'8', '1', '0', '2'}
{0, True, '8', '0', '1', '2'}
{1, 2}
{1, 2, 3, 4}
{1, 3}
{'4', '1', '3', '2'}

(三),移除元素,清空集合,其他函数

set1=set("2018");
print(set1,"  元素长度  ",len(set1));
print("判断元素是否在集合中存在","2" in set1);
set1.remove("2");print("使用remove()删除元素: %s" % set1);
#set1.remove("4");print("使用remove()删除元素: %s" % set1);#没有该元素会报错 KeyError: '4'
set1.discard("0");print("使用discard()删除元素: %s" % set1);
set1.pop();print("使用pop()随机删除元素: %s" % set1);
set1.clear();print("使用clear()清空集合: %s" % set1);
console:
{'2', '1', '8', '0'}   元素长度   4
判断元素是否在集合中存在 True
使用remove()删除元素: {'1', '8', '0'}
使用discard()删除元素: {'1', '8'}
使用pop()随机删除元素: {'8'}
使用clear()清空集合: set()

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值