Python基础任务三

1.dict字典

a. 定义

映射是一个按照任意值排序的对象组成的数据集合,这些任意值被称为键(key),字典是Python中唯一的映射类型,字典中的键可以是不同类型,值(value)是任意对象,并且可以是不同类型。
字典是用大括号{ }定义的,每个项目都是key:value形式。

b. 创建

字典由键(key)和对应值(value)成对组成。字典也被称作关联数组或哈希表。基本语法如下:

dict = {‘Alice’: ‘2341’, ‘Beth’: ‘9102’, ‘Cecil’: ‘3258’}

注意:
每个键与值用冒号隔开(:),每对用逗号,每对用逗号分割,整体放在花括号中({})。
键必须独一无二,但值则不必。
值可以取任何数据类型,但必须是不可变的,如字符串,数组或元组。

c. 字典的方法

字典的访问

dict1 = {‘q’:12,‘w’:24,2:‘haha’}
print(dict1.keys()) #返回所有的健
print(dict1.values()) #返回所有的值
print(dict1[2]) #访问字典中键-2的值
print(dict1.get(‘q’)) #返回字典中键’q’的值
print('w’in dict1) #字典中键’w’是否存在

#输出结果:
#dict_keys([‘q’, ‘w’, 2])
#dict_values([12, 24, ‘haha’])
#haha
#12
#True

字典的修改

dict[‘key’] = value,若key为新的键,则为字典新插入一个值,否则,修改改键所对应的值;
dict.setdefault(key,value),只能新增键值对

dict1 = {‘q’:12,‘w’:24,2:‘haha’}
dict1[‘Tom’] = ‘a boy’ #插入一个新的键值对
dict1[‘q’] = ‘a girl’ #修改值
dict1.setdefault(4,‘Beijing’) #新增一个键值对
print(dict1)
#dict1 = {‘q’: ‘a girl’, ‘w’: 24, 2: ‘haha’, ‘Tom’: ‘a boy’, 4: ‘Beijing’}

删除字典

pop() ,popitem(), del , clear()

dict1 = {‘q’: ‘a girl’, ‘w’: 24, 2: ‘haha’, ‘Tom’: ‘a boy’, 4: ‘Beijing’}
dict1.pop(2) #pop方法必须指定键
print(dict1)
del dict1[4]
print(dict1)
dict1.popitem() #随机删除一个
print(dict1)
dict1.clear() #清空字典
print(dict1)
del dict1 #删除字典
#输出:
#{‘q’: ‘a girl’, ‘w’: 24, ‘Tom’: ‘a boy’, 4: ‘Beijing’}
#{‘q’: ‘a girl’, ‘w’: 24, ‘Tom’: ‘a boy’}
#{‘q’: ‘a girl’, ‘w’: 24}

2.集合

a… 特性

集合是一种无序且键唯一的数据类型

b 创建

set()方法;{}大括号创建

c. 方法

集合常用的方法列表
函数 描述
a.add(x) 将元素x加入集合a
a.clear() 清空集合
a.remove(x) 将元素x 从集合a移除
a.discard(x) 将元素x 从集合a移除
a.pop() 移除任意元素
a.union(b) a和b中所有不同的元素
a.update(b) 将集合为更新为a和b的并集
a.intersection_update(b) a、b中同时包含的元素
a.difference(b) a不在b的元素
a.difference_update(b) 更新a为a不在b的元素
a.symmetric_difference_update(b) 所有在a或b中,但不是同时在a和b中
a.symmetric_difference(b) 更新a为所有在a或b中,但不是同时在a和b中
a.issubset(b) 如果a包含于b则返回true
a.issuperset(b) 如果a包含b则返回true
a.isdisjointt(b) 如果a、b无交集则返回true

3. 判断语句(要求掌握多条件判断)

(1)单条件判断

  if 判断条件:
  	执行语句
else:
  	执行语句

(2)多重判断

if 判断条件:
执行语句  
elif 判断条件:
执行语句   
else:
age = 25
if age <= 30:
print(True)
else:

4. 三目表达式

(1)为真时的结果 if 判断条件 else 为假时的结果

x = 20
x = x+1 if x%100 else x #判断为真
print(x) # 21
x = 22
x = x+1 if x%10
0 else x #判断为假
print(x) # 22

(2)numpy的where(判断条件,为真时的处理,为假时的处理)

import numpy as np
x = 20
x = np.where(x%10==0, x+1, x)

5. 循环语句

for()循环:

for 变量 in 数据列表:
循环体
[if 变量 == 值:
break] #跳出循环
else:
执行语句

while 循环

while 判断条件:
循环体


猜你喜欢

转载自blog.csdn.net/weixin_41741008/article/details/89048197