Python语言基础学习(三)

1. 字典dict

a. 定义

  • 字典dict相当于其他语言中的map,使用键-值(key-value)存储,用key来查找到value(用key通过哈希算法计算value的存储位置)
  • 具有极快的查找速度,是用空间来换取时间的一种方法
  • 在需要将两种元素相关联的时候使用
  • 注意字典的无序性,dict内部存放的顺序和key放入的顺序是没有关系的
  • 注意key的特性:
    key具有不可变性,所以key可以是字符串、数字或元组,而不能是list这种可变的数据类型的数据;(ps:是单个key的不可变性,dict本身是可变对象)(补充一句,对于不可变对象str/num/tuple来说,调用对象自身的任意方法不会改变该对象自身的内容,只会创建新的对象并返回,这样就保证了不可变对象本身永远是不可变的;而可变对象dict/set/list调用改变自身的方法时会改变自身)
    key具有唯一性,所以key不能重复,而value可以是重复的。

b. 创建

字典的标志是{k1:v1, k2:v2,...,kn:vn},key可以是字符串、数字或元组,不同的key可以是不同的数据类型,value可以是任意数据类型,举个例子:

# dict
d1 = {'xiaoming':100, 'xiaohong':100, 'xiaocong':99} #学生姓名-成绩对

c. 字典的方法

访问

dict1[key1],如果用字典里没有的键访问数据,会输出KeyError错误。要避免key不存在的错误,有两种办法:

  • 一是通过in判断key是否存在: key1 in dict1,如果在返回True,不在返回False
  • 二是通过dict提供的get()方法,如果key不存在,可以返回None,或者自己指定的value:
    dict1.get(key1)如果dict1中有key1,返回key1对应的value1,如果dict1中没有key1,返回None;
    dict1.get(key1, -1)如果dict1中有key1,返回key1对应的value1,如果dict1中没有key1,返回给定的值-1。

添加

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
 
dict['Age'] = 8 # 更新
dict['School'] = "RUNOOB" # 添加

删除

  • 删除单个key-value对用dict1.pop(key1) 或 del dict1[key1]
  • 清空字典中的所有key-value对用dict1.clear(),此时字典dict1仍然存在
  • 删除字典用del dict1

其他方法

 |  keys(...)
 |      D.keys() -> a set-like object providing a view on D's keys
用法是dict.keys(),以列表返回一个字典所有的键
 |  

 |  values(...)
 |      D.values() -> an object providing a view on D's values 
以列表返回字典中的所有值

 |  
 |  items(...)
 |      D.items() -> a set-like object providing a view on D's items 
以列表返回可遍历的(键, 值) 元组数组

 |  copy(...)
 |      D.copy() -> a shallow copy of D
 |  
 |  fromkeys(iterable, value=None, /) from builtins.type
 |      Returns a new dict with keys from iterable and values equal to value. 创建一个新字典,以序列 seq 中元素做字典的键,val 为字典所有键对应的初始值
 |  popitem(...)
 |      D.popitem() -> (k, v), remove and return some (key, value) pair as a
 |      2-tuple; but raise KeyError if D is empty. 随机返回并删除字典中的一对键和值。
 |  
 |  setdefault(...)
 |      D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D 和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default
 |  
 |  update(...)
 |      D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
 |      If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
 |      If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
 |      In either case, this is followed by: for k in F:  D[k] = F[k]  dict1.update(dict2)把字典dict2的键/值对更新到dict1里

函数

 

2. 集合set

集合set是一个无序不重复元素集,可以删除重复数据,还可以计算交集、差集、并集等。

a. 特性

  • set是一组key的集合,与dict有点类似,但不存储value
  • 因为key不能重复,所以set中没有重复的key
  • key同样具有不可变性(ps:是单个key的不可变性,set是可变对象)
  • 因为集合中元素的无序性,set中key是没有顺序的

b. 创建

set的标志是{}。对一个list套用set,就会得到set s,s={1,2,3} ,如果list中有重复的元素会被自动过滤掉:

s = set([1, 2, 3])

c. 方法

 | add(...)
 |      Add an element to a set.

 |      
 |      This has no effect if the element is already present. 添加元素

 |  
 |  clear(...)
 |      Remove all elements from this set.
 |  
 |  copy(...)
 |      Return a shallow copy of a set.
 |  
 |  difference(...)
 |      Return the difference of two or more sets as a new set. 差集,也可以用s1-s2

 |      
 |      (i.e. all elements that are in this set but not the others.)

 |  
 |  difference_update(...)
 |      Remove all elements of another set from this set.
 |  
 |  discard(...)
 |      Remove an element from a set if it is a member.
 |      
 |      If the element is not a member, do nothing.
 |  
 |  intersection(...)
 |      Return the intersection of two sets as a new set.  交集,也可以用s1&s2
 |      
 |      (i.e. all elements that are in both sets.)

 |  
 |  intersection_update(...)
 |      Update a set with the intersection of itself and another.
 |  
 |  isdisjoint(...)
 |      Return True if two sets have a null intersection. 是否不相交
 |  
 |  issubset(...)
 |      Report whether another set contains this set. 是否是子集
 |  
 |  issuperset(...)
 |      Report whether this set contains another set. 是否包含
 |  
 |  pop(...)
 |      Remove and return an arbitrary set element.
 |      Raises KeyError if the set is empty.
 |  
 |  remove(...)
 |      Remove an element from a set; it must be a member. 删除某元素s.remove(key1)

 |      
 |      If the element is not a member, raise a KeyError.
 |  
 |  symmetric_difference(...)
 |      Return the symmetric difference of two sets as a new set.
 |      
 |      (i.e. all elements that are in exactly one of the sets.)
 |  
 |  symmetric_difference_update(...)
 |      Update a set with the symmetric difference of itself and another.
 |  
 |  union(...)
 |      Return the union of sets as a new set. 并集,也可以用s1|s2

 |      
 |      (i.e. all elements that are in either set.)

 |  
 |  update(...)
 |      Update a set with the union of itself and others.

3. 判断语句

python中没有switch,只有if:

if <条件判断1>:
    <执行1>
elif <条件判断2>:
    <执行2>
elif <条件判断3>:
    <执行3>
else:
    <执行4>

判断条件可以包含>(大于)、<(小于)、==(等于)、!=(不等于)、>=(大于等于)、<=(小于等于)、and(与,表示前后的条件同时成立)、or(或,表示前后有条件成立即可)、not(不是)、in(在list或set中)、not in(不在list或set中)、is(两个标识符的引用一致)、not is(两个标识符的引用不一致),当if有多个条件时可使用括号来区分判断的先后顺序,括号中的判断优先执行,此外 and 和 or 的优先级低于>(大于)、<(小于)等判断符号:

age = 20
if age >= 6:
    print('teenager')
elif age >= 18:
    print('adult')
else:
    print('kid')

 还有一种简略形式的判断条件,只要x非零数值、非空字符串、非空list等就判断为True,否则为False:

if x:
    print('True')

4. 三目表达式

Python里的三目表达式和C++等语言里的顺序不太一样,Python里的是:

条件为真时的结果 if 判段的条件 else 条件为假时的结果 

如:x = x+1 if x%2==1 else x

5. 循环语句

Python的循环有两种:

  • 一种是for...in循环,通常配合range()序列生成函数使用:
sum = 0
for x in range(10):
    sum = sum + x
print(sum)
  • 第二种循环是while循环,只要条件满足就不断循环,条件不满足时退出循环,如:
sum = 0
n = 99
while n > 0:
    sum = sum + n
    n = n - 2
print(sum) 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值