码迷,mamicode.com
首页 > 其他好文 > 详细

二.列表,元组,集合,字典的基础应用

时间:2019-12-12 20:02:04      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:适合   title   合并   存在   删除   key   变化   for循环   lis   

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

 

 

 

 

 

 

 

 

二.列表,元组,集合,字典的基础应用

标签:适合   title   合并   存在   删除   key   变化   for循环   lis   

原文地址:https://www.cnblogs.com/huiguizhe/p/11988302.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!