9、字典(Dict)
clear()、len()、dict.fromkeys(seq1,seq2)新建字典、dict.items()、dict.keys()、dict.values()
dict(zip(list1,list2))
增dict[‘a’]=A
删del dict[‘a’]、dict.pop()需要指定对象、dict.popitem()默认弹出最后
改dict[‘a’]=A、a.update(b)更新值、dict.setdefault(‘a’,15)设置不可改、dict.get(‘a’,15)
查dict.get(‘points’,’None’)有出无None
遍历dict.items()、dict..keys()、dict..values()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| song = """Are you sleeping, are you sleeping, Brother John, Brother John? Morning bells are ringing, morning bells are ringing. Ding ding dong, Ding ding dong.""" mydict = {} print("原始歌曲") print(song)
songLower = song.lower() print("小写歌曲") print(songLower)
for ch in songLower: if ch in ".,?": songLower = songLower.replace(ch,'') print("不再有标点符号的歌曲") print(songLower)
songList = songLower.split() print("以下是歌曲列表") print(songList)
for wd in songList: if wd in mydict: mydict[wd] += 1 else: mydict[wd] = 1 print("以下是最后执行结果") print(mydict)
word = 'deepstone' alphabetCount = {alphabet:word.count(alphabet) for alphabet in word} print(alphabetCount)
|
10、集合(Set)
set()、基数(cardinality)、len()、clear()
基础操作:&intersection()、|union()、-difference()、symmetric_difference()取不同元素组成新集合
==、!=、in、not in、A.intersection_update(B,C)三者交集更新A值,update()相加
isdisjoint()共同元素、issubset()是子集、isuperset()是超集
增 add()、update()
删 remove()、discard()可删除不存在的元素、pop()
拷贝 copy()
不可变集合(forzenset不可变且是哈希的)冻结集合(immutable set)
1 2 3 4
| word = 'deepstone' alphabetCount = {alphabet:word.count(alphabet) for alphabet in set(word)} print(alphabetCount)
|
11、函数设计
参数:位置参数、关键字参数(传入keyword arguments)、默认值(参数列表)
列表参数、任意数量参数 、关键词参数 * 、 多返回值是tuple
文件字符串Docstring(def函数下的注释)、闭包closure(内部函数外环境变量值)
递归式函数设计recursive、堆栈stack、pop、push、sys.getrecursionlimit()
locals()、globals()、lambda arg1[,….]:expresion 匿名函数(anonymous function)
筛选列表filter、迭代列表map、装饰器(decorator)传入一个函数,传回留一个函数@upper
str.replace(ch,’ ‘)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| mylist = [1,2,3,4,5,6,7]
lambda x:(x%2==1)
print(list(filter(lambda x:(x%2==1),mylist)))
print(list(map(lambda x:(x%2==1),mylist)))
from functools import reduce
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| def upper(func): def newFunc(args): oldresult = func(args) newresult = oldresult.upper() print('函数名称 : ', func.__name__) print('函数参数 : ', args) return newresult return newFunc @upper def greeting(string): return string
print(greeting('Hello! iPhone'))
def upper(func): def newFunc(args): oldresult = func(args) newresult = oldresult.upper() return newresult return newFunc def bold(func): def wrapper(args): return 'bold' + func(args) + 'bold' return wrapper
@bold @upper def greeting(string): return string
print(greeting('Hello! iPhone'))
def gcd(a, b): return a if b == 0 else gcd(b, a % b)
def lcm(a, b): return a * b // gcd(a, b)
a, b = eval(input("请输入2个整数值 : ")) print("最大公约数是 : ", gcd(a, b)) print("最小公倍数是 : ", lcm(a, b))
|