knights ={'gallahad':'the pure','robin':'the brave'}for k, v in knights.items():# 同时获得字典的key和valueprint(k, v)==>gallahad the pure
robin the brave
for i, v inenumerate(['tic','toc','toe']):print(i, v)==>0 tic # 同时获得序列的索引和内容1 toc
2 toe
questions =['name','quest','favorite color']
answers =['lancelot','the holy grail','blue']for q, a inzip(questions, answers):print('What is your {0}? It is {1}.'.format(q, a))# 同时遍历两个或更多的序列sorted([])、reversed([])# 顺序、逆序遍历
sorted()函数与sort()函数的区别: 1.sort()是应用在
l
i
s
t
list
list上的方法,sorted()可以对所有可迭代的对象进行排序操作。 2.sort()方法返回的是对已经存在的列表进行操作,而内建函数sorted()方法返回的是一个新的
l
i
s
t
list
list,而不是在原来的基础上进行的操作。
reversed()函数:反转迭代器,不排序,返回迭代器(而不是
l
i
s
t
list
list)
zip()函数:将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的zip对象。
import random
X =[1,2,3,4,5,6]
y =[0,1,0,0,1,1]
zipped_data =list(zip(X, y))# 将样本和标签一一对应组合起来,并转换成list类型方便后续打乱操作,shuffle不能对zip对象操作
random.shuffle(zipped_data)# 使用random模块中的shuffle函数打乱列表,原地操作,没有返回值
new_zipped_data =list(map(list,zip(*zipped_data)))# zip(*)反向解压,map()逐项转换类型,list()做最后转换
new_X, new_y = new_zipped_data[0], new_zipped_data[1]# 返回打乱后的新数据print('X:', X,'\n','y:', y)print('new_X:', new_X,'\n','new_y:', new_y)
import time
# while True:# try:# print("Wheeeee! You can't stop me")# time.sleep(0.2)# except:# print("Whatever I'm still running!")whileTrue:try:print("Wheeeee! You can't stop me")
time.sleep(0.2)except Exception:print("Whatever I'm still running!")
涉及到固定数据的检索等操作时,集合(set)比列表(list)效率要高。
Mutable defaults问题,当期望函数形参类型是列表时注意一下。
defadd_names_to_agg_list(names, aggregate_list=[]):for name in names:
aggregate_list.append(name)return aggregate_list
print(add_names_to_agg_list(['Mary','Rick','Morty']))print(add_names_to_agg_list(['Mary','Rick','Morty']))==>['Mary','Rick','Morty']==>['Mary','Rick','Morty','Mary','Rick','Morty']---------------------------------------------------------defadd_names_to_agg_list(names, aggregate_list=None):ifisinstance(aggregate_list,type(None)):
aggregate_list =[]# or# if not aggregate_list:# aggregate_list = []for name in names:
aggregate_list.append(name)return aggregate_list
print(add_names_to_agg_list(['Mary','Rick','Morty']))print(add_names_to_agg_list(['Mary','Rick','Morty']))==>['Mary','Rick','Morty']==>['Mary','Rick','Morty']
常用函数关于遍历knights = {'gallahad': 'the pure', 'robin': 'the brave'}for k, v in knights.items(): # 同时获得字典的key和value print(k, v)==>gallahad the pure robin the brave for i, v in enumerate(['tic', 'toc', 'toe']): print(i, v)==>0 tic