python基礎-內置函數(2)
阿新 • • 發佈:2017-11-12
logs 區別 welcom map 創建 class ict 叠代 pre
一、創建集合、字典、列表、元組的函數
1、創建集合:set()
s=set() #生成一個空集合 s1=set([11,22,33,44,11]) #生成一個集合
2、創建字典:dict()
a = dict(one=1, two=2, three=3) b = {‘one‘: 1, ‘two‘: 2, ‘three‘: 3} c = dict(zip([‘one‘, ‘two‘, ‘three‘], [1, 2, 3])) d = dict([(‘two‘, 2), (‘one‘, 1), (‘three‘, 3)]) e = dict({‘three‘: 3, ‘one‘: 1, ‘two‘: 2})
3、創建列表:list()
a=list([11,22,33,44])
4、創建元組: tuple()
a = tuple([1,3,4,5,5])
二、篩選:filter(函數,可叠代的對象)
def f1(a): if a>22: return True li=[11,22,33,44,55,66] ret=filter(f1,li) print(list(ret)) #篩選出大於22的列表元素
三、map函數:map(函數,可叠代的對象)
li=[11,22,33,44,55,66] ret=map(lambda a:a+200,li)
結果:[211, 222, 233, 244, 255, 266]
filter和map的區別在於:filter的參數中,函數返加True,則把可叠代對象中的元素添加到結果中,而map的參數中,是直接把函數的返回值添加到結果中
四、zip函數
l1=[‘Welcome‘,11,33,44] l2=[‘to‘,11,33,44] l3=[‘Beijin‘,11,33,44] r=zip(l1,l2,l3) temp=list(r)[0] ret=‘ ‘.join(temp) print(ret)
結果:Welcome to Beijin
python基礎-內置函數(2)