一、元組: tuple
Python 的元組與列表類似,不同之處在於元組的元素不能修改。
元組中的元素值是不允許刪除的,但我們可以使用del語句來刪除整個元組
tup2 = (111, 22, 33, 444, 55, 6, 77 ) for x in (tup2): #遍歷 print(x) list2 = [111, 22, 33, 444, 55, 6, 77 ] tup2 = tuple(list2) #將列表轉變為元組
二、列表: list
遍歷列表:
#遍歷列表 list1 = [1, 2, 3, 6, 5, 4] for x in list1: print(x, end=",") # 運行結果:1,2,3,6,5,4, for i in range(len(list1)): print("序號:", i, " 值:", list1[i]) for i, val in enumerate(list1): print("序號:", i, " 值:", val) for i in list1: idx = list1.index(i) # 索引 if (idx < len(list1) - 1): print(i, '---------', list1[idx + 1])
排序列表、判斷元素是否在列表中:
list1 = [1,2,3,6,5,4] #排序列表(正序) list1.sort() for x in list1: print(x, end=",") #運行結果:1,2,3,4,5,6, print("") #排序列表(倒序) list1.reverse() for x in list1: print(x, end=",") #運行結果:6,5,4,3,2,1, print("") #判斷元素是否存在於列表中 if 5 in list1: print("5 在list1中") #在末尾追加新的元素 list1.append(555) list1.append(555) print(list1) #統計某個元素在列表中出現的次數 print("出現",list1.count(555),"次") #移除元素,並返回值(默認是移除最后一個) print(list1.pop(0)) # 移除第一個 print(list1.pop()) # 移除最后一個
隨機列表
import random #返回一個隨機的項目 print(random.choice(range(100))) print(random.choice([1, 2, 3, 5, 9])) print(random.choice('Hello World')) ls1 = [20, 16, 10, 5]; random.shuffle(ls1) #返回重新洗牌列表,隨機
把數字列表轉換為字符列表
ls1 = [1,2,4,5] ls2 = [str(i) for i in ls1] print(ls2) # ['1', '2', '4', '5']
三、字典: dict
dict = {'name': 'pp', 'age': 20, "gender": "man"} dict["name"] = "sss" for key in dict.keys(): # 遍歷字典。字典的 keys() 方法以列表返回可遍歷的(鍵) 元組數組。 print(key) for val in dict.values(): # 遍歷字典。字典的 values() 方法以列表返回可遍歷的(值) 元組數組。 print(val) for key, val in dict.items(): # 遍歷字典。字典的 items() 方法以列表返回可遍歷的(鍵, 值) 元組數組。 print(key, " : ", val)
字典的多級嵌套:
citys={ '北京':{ '朝陽':['國貿','CBD','天階'], '海淀':['圓明園','蘇州街','中關村','北京大學'], '昌平':['沙河','南口','小湯山',], '懷柔':['桃花','梅花','大山'] }, '河北':{ '石家庄':['石家庄A','石家庄B','石家庄C'], '張家口':['張家口A','張家口B','張家口C'] } } for i in citys['北京']: print(i) for i in citys['北京']['海淀']: print(i)
四、集合: set
集合(set)是一個無序不重復元素的序列。 基本功能是進行成員關系測試和刪除重復元素。
集合無序,元素不能重復。
去重:將列表轉化為集合,集合再轉化為列表,就可以去重。
可以使用大括號 { } 或者 set() 函數創建集合,注意:創建一個空集合必須用 set() 而不是 { },因為 { } 是用來創建一個空字典。
student = {'Tom', 'Jim', 'Mary', 'Tom', 'Jack', 'Rose'} print(student) # 輸出集合,重復的元素被自動去掉 {'Mary', 'Jim', 'Rose', 'Jack', 'Tom'} # 成員測試 if('Rose' in student) : print('Rose 在集合中') else : print('Rose 不在集合中') #Rose 在集合中
從一個大集合里,去除一個小集合
set000 = set("123456789") set1 = set(["2", "3", "5", "5", "6", "0"]) print(set000 - set1) #{'7', '8', '9', '1', '4'}
補充:相互轉換
1、元組 => 列表
tuple1 = (123, 'haha', 'she', 'hehe') list1 = list(tuple1) #將元組轉換為列表。運行結果:[123, 'haha', 'she', 'hehe'] print(list1)
2、字符串 <=> 列表
str1 = '天地玄黃宇宙洪荒' list1 = list(str1) # 字符串轉為列表 str2 = "".join(list1) # 列表轉為字符串 print(str2) str1 = '天地,玄黃,宇宙,洪荒' list1 = str1.split(",") # 字符串轉為列表 print(list1) str1 = '天地玄黃宇宙洪荒' str2 = str1[::-1] # 字符串倒序 print(str2)
迭代器、生成器: http://www.runoob.com/python3/python3-iterator-generator.html
迭代器有兩個基本的方法:iter() 和 next()
import sys # 引入 sys 模塊 list = [1, 2, 3, 4] it = iter(list) # 創建迭代器對象 while True: try: print(next(it)) except StopIteration: sys.exit()
使用了 yield 的函數被稱為生成器(generator)。 跟普通函數不同的是,生成器是一個返回迭代器的函數,只能用於迭代操作
import sys def fibonacci(n): # 生成器函數 - 斐波那契 a, b, counter = 0, 1, 0 while True: if (counter > n): return yield a a, b = b, a + b counter += 1 f = fibonacci(10) # f 是一個迭代器,由生成器返回生成 while True: try: print(next(f), end=" ") except StopIteration: sys.exit()
Map,Filter,Reduce
- Map 會將一個函數映射到一個輸入列表的所有元素上。 (這個可以同時對list里的所有元素進行操作,並以列表方式給出返回值。)
- filter 過濾列表中的元素,並且返回一個由所有符合要求的元素所構成的列表。 (這個可以被用來過濾原有的list,並把過濾結果放進新的list里。)
- 當需要對一個列表進行一些計算並返回結果時,Reduce 是個非常有用的函數。 (這個可以隊列表順序執行算術運算。)
http://docs.pythontab.com/interpy/Map_Filter/Map/
ls1 = [1, 2, 3, 4, 5] ls2 = list(map(lambda x: x ** 2, ls1)) #加了list轉換,是為了python2/3的兼容性。 在python2中map直接返回列表,但在python3中返回迭代器 print(ls2) # [1, 4, 9, 16, 25] ls1 = range(-5, 5) ls2 = filter(lambda x: x > 0, ls1) print(list(ls2)) # [1, 2, 3, 4] from functools import reduce product = reduce((lambda x, y: x * y), [1, 2, 3, 4]) # 計算一個整數列表的乘積 print(product) # 24
裝飾器:
def a(arg): pass def b(arg): pass def c(arg): pass def decorator(func): def wrapper(*arg, **kw) print ('Start ---' , func) return func(*arg, **kw) return wrapper a = decorator(a) b = decorator(b) c = decorator(c)
https://www.zhihu.com/question/26930016
...