二.列表,元组,集合,字典的基础应用
Posted huiguizhe
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二.列表,元组,集合,字典的基础应用相关的知识,希望对你有一定的参考价值。
1.列表的应用(list [ ] 非常适合用于存储在程序运行期间可能变化的数据集)
1.1 range()函数
Experiments = [] for Experiment in range(1,10): Experiments.append(Experiment**2) print(Experiments) >>[1, 4, 9, 16, 25, 36, 49, 64, 81]
1.2 列表解析将for循环和创建新元素的代码合并成一行,并自动附加新元素
Experiments =[value**2 for value in range(1,10)] print(Experiments) >>[1, 4, 9, 16, 25, 36, 49, 64, 81]
1.3 切片和遍历切片
players = [‘football‘,‘basketball‘,‘tennis‘] print("I like playing:") for player in players: print(player.title())
1.4 复制列表
players_one = players[:]
1.5 format()
name = ‘{n} like playing football‘.format(n=‘alex‘) print(name)
>>alex like playing football
2.元组(tuple() 不可改)
2.1 遍历
name = ( ‘liu‘,‘li‘) for i in name: print(i) >>liu >>li
2.2 索引
name = ( ‘liu‘,‘li‘) print(name[0])
2.3 运算符也可以(加,乘,以及len())
name = ( ‘liu‘,‘li‘) number =(1,2) print(name + number) >>(‘liu‘, ‘li‘, 1, 2)
3.集合(set{},去重,关系测试,无序)
3.1 关系测试
set_one = { 1,4,6} set_two = {1, 5,"a" } print(set_one.intersection(set_two))#交集 print(set_one & set_two)#进阶 >>{1} >>{1} print(set_one.difference(set_two))#差集 print(set_one - set_two) >>{4, 6} >>{4, 6} print(set_one.union(set_two))#并集 print(set_one | set_two) >>{1, ‘a‘, 4, 5, 6} >>{1, ‘a‘, 4, 5, 6} print(set_ont ^ set_two)#去重复并集
3.2 集合添加
set_two = {1, 5,"a" } set_two.add(13)#只能单个添加 print(set_two) >>{‘a‘, 1, 13, 5} set_two.update([14,"apple"])#多个添加 print(set_two) >>{1, 5, ‘apple‘, 13, 14, ‘a‘} set_two.update({23},["jiu"])#测试 print(set_two) >>{1, 5, 23, ‘jiu‘, ‘a‘, 13}
3.3集合删除
set_two = {1, 5,"a" } set_two.remove(5)#指定删除元素 ,不存在报错 print(set_two) >>{1, ‘a‘} set_two.discard(5)#也是指定删除元素,不存在不报错 set_two.pop()#随机删除一个
4.字典(dict() 是无序的,且key唯一,天生去重)
4.1 打印和替换
info = {"key1":"value1", "key2":"value2"} print(info["key1"])#打印key1的值,没有则报错 >>value1 info["key1"] = "值1"#替换或添加 print(info) >>{‘key1‘: ‘值1‘, ‘key2‘: ‘value2‘}
4.2 删除键值对
info = {"key1":"value1", "key2":"value2"} info.pop("key1")#删除键值对 print(info) >>{‘key2‘: ‘value2‘} del info["key1"]#del 删除键值对 print(info) info.popitm()#随机删除
4.3
info = {"key1":"value1", "key2":"value2"} for i in info: print(i , info[i]) >>key1 value1 >>key2 value2 for k,v in info.items():#info.items,先把info改为列表再赋值 print(k,v) >>key1 value1 >>key2 value2
以上是关于二.列表,元组,集合,字典的基础应用的主要内容,如果未能解决你的问题,请参考以下文章
Python基础数据结构:列表 | 元组 | 集合 | 字典