Python学习日记(2)Python内建集合及操作

  列表

 列表是零个或多个Python对象的一个序列,这些对象通常称之为项;

 列表示例:

[]    #An empty list

["test"]    #A list of one string 

["test","python"]     #A list of two string

["test","python",10]    #A list of two string and an int

["test",["python",10]]    #A list with a nested list

和字符串一样,可以对列表进行切片和链接,但是注意,切片和链接后,返回的依然是一个列表;

与字符串不同的是,列表是可变的(字符串不可变),这意味着,你可以针对列表进行替换,插入,删除等操作;

当然,如果你对列表进行了操作(比如替换,插入,删除),这意味着2个后果:

  1,你改变了列表的结构

  2,操作后返回的列表是一个新的列表而不是原列表

如果你想趣味的记住列表的一些操作,你可以认为,Python针对列表开发了一个"修改器":

让我们看看"修改器"的功能有什么:

test_list = []    #创建空列表

test_list.append(2) #列表中添加项:2

test_list.append(33) #列表中添加项:33

test_list.pop() #弹出列表中最后一个项(我习惯理解是剪切,因为弹出的项可以用)

test_list.insert(0,25) #在列表下标0的位置插入项:25

test_list.insert(1,66) #在列表下标1的位置插入项:66

test_list.sort() #列表从小到大排列

test_list.sort(severse=True) #列表从大到小排序

test_list.severse() #将列表逆序,不改变列表中项原来的顺序

test_list.remove(25) #删除列表中的项:25

test_list.count(25) #返回列表中25出现的次数 

test_list.extend(list) #将list合并到test_list中

"".join(test_list) #将test_list列表内的项转为字符串

"python_string".split() #将字符串切片为列表

  元组

元组是项的一个不可变序列,且元组中最少包含2个项,表示方法是用括弧括起来,元组实际上与列表一样,只不过元组没有“修改器”,元组是不可变序列;

(33,44) #一个元组,包含项:33和44

当然,上图的元组,你没发用列表的修改器方法进行修改。

  遍历序列

for循环用来遍历一个序列(字符串,元组,列表)中的项,比如遍历一个列表:

test1_list = [22,33,44,"python"]

for item in test1_list:
    print(item)

---------------------------------------------
22
33
44
python
[Finished in 0.2s]

  字典

字典包含零个或多个条目,每一个条目都一个唯一的键和对应的值相关联。

键一般是字符串或者整数,而值可以是Python中的任何对象;

字典的键和值被包含在一对花括号中:

{} 

{"name":"python"}

{"name":"python","id":6520}

{"name":"python","id":6520,"item":[66,88]}

当然,字典和列表一样,是可变类型,与元组不可变类型不同,Python中同样为可变类型字典也添加了“修改器”:

test_dict = {} #创建一个空字典

test_dict["name"] = "python"  #字典中添加键name和对应值python

#>>>{'name': 'python'}

test_dict["id"] = 18 #字典中添加键id和对应的值18

#>>>{'name': 'python', 'id': 18}

test_dict.get("id") #查询字典中键id对应的值

del test_dict["id"] #删除字典中键id和其对应的值

  遍历字典

test_dict = {'name': 'python', 'id': 18}

for a in test_dict.keys():    #遍历字典中所有的键
    print(a)

for b in test_dict.values(): #遍历字典中所有的值
    print(b)

for c in test_dict.items():  #遍历字典中每一对键和值,并按对遍历后生成元组出储存
    print(c)

---------------------------------------------
name
id
python
18
('name', 'python')
('id', 18)
[Finished in 0.1s]

  字典的pop()和get()方法

dict_test = {"id":6520}

a = dict_test.pop("ss","未找到值")

#>>>未找到值

b = dict_test.pop("id","未找到值")

#>>>6520

print(dict_test)

#>>>{}

对于字典来说,get()和pop()方法可以接收2个参数,一个键和一个默认值,搜索或者弹出失败,会返回默认值;

如果搜索成功或弹出成功,则会返回搜索和弹出键对应的值;

猜你喜欢

转载自www.cnblogs.com/shsm/p/9278956.html