程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python 推導,內含,迭代器

編輯:Python

Python語法–推導或內含

  • list comprehension操作可以將一個序列類型的數據集推導出另一個序列類型的數據集:
  1. 典型的情況:
for i in aiterator
  1. 利用推導獲取一個平方數列表
square = [i * i for i in range(1, 11)]
  • 以上情況同如下循環
for i in range(1, 11):
square.append(i * i)
  1. 字典推導語法如下格式:
{
key_exp:value_exp for key_exp,value_exp in aiterator}
  • 具體案例如下:
keys = ['name', 'age', 'weight']
values = ['jiamin', '28', '81']
infoMap = {
k: v for k, v in zip(keys, values)}
推導+邏輯處理
  1. 使用if語句實現選擇處理遍歷的元素,如下語法規則:
for i in aiterator if ...
{
key_exp:value_exp for key_exp,value_exp in aiterator if ...}
  • 具體案例如下
##取偶數
square_odd = [i * i for i in range(1, 11) if i * i % 2 == 0]
##只取年齡
infoMap_odd = {
k: v for k, v in zip(keys, values) if k == 'age'}
##通過字典生成字典
dict_one = {
'name': 'jiamin', 'age': '28', 'weight': '81'}
dict_two = {
k: v for k, v in dict_one.items() if k == 'name'}

python中迭代器

  • 迭代器是Python中一個數據量對象的容器,當使用時候每次都從其中取出一個,直到取完
自定義迭代器
  • 只要定義一個實現迭代器協議的方法類即可,主要協議方法與入學兩個
__iter__() ## 方法放回對象本身,他是for語句使用迭代器的要求
__next__() ## 方法返回容器中下一個元素或數據,當容器中數據用完,應該引發StopIteration
  • 自定義迭代器代碼如下:
## 自定義代器遍歷
class MyIterator:
def __init__(self, x=2, xmax=100):
self.__mul, self.__x = x, x
self.__xmax = xmax
def __iter__(self):
return self
def __next__(self):
if self.__x and self.__x != 1:
self.__mul *= self.__x
if self.__mul <= self.__xmax:
return self.__mul
else:
raise StopIteration
else:
raise StopIteration
if __name__ == '__main__':
myiter = MyIterator()
for i in myiter:
print('自定義迭代器: ', i)
內置迭代器工具
  • Python中內建了一個用於產生迭代器的函數iter(),另外一個標准庫的itertools模塊還有豐富的迭代器工具:
  • 內置迭代器工具實例:
## 內建迭代器遍歷
class Counter:
def __init__(self, x=0):
self.x = x
counter = Counter()
def used_iter():
counter.x += 2
return counter.x
for i in iter(used_iter, 8):
print("內建迭代器遍歷: ", i)
itertools模塊中常用工具函數
import itertools
## 迭代器工具類
## 從1 開始,每此以3 為步迭代
def countTest():
for i in itertools.count(1, 3):
print(i)
if i >= 10:
break
##無線循環迭代
def cycleTest():
for i in itertools.cycle([1, 2, 3]):
print(i)
## 循環迭代 輸出: [2, 2, 2]
def repeatTest():
print(list(itertools.repeat(2, 3)))
##chain(p,q,...)鏈接迭代,將p,q連接起來迭代輸出:[1, 2, 3, 4, 5, 6]
def chainTest():
print(list(itertools.chain([1, 2, 3], [4, 5, 6])))
## compress(data,selectors) 根據selectors中的值選擇迭代data序列中的值 輸出: [1, 3]
def compressTest():
print(list(itertools.compress([1, 2, 3, 4], [1, None, True, False])))
## dropwhile(pred,seq) 當pred對序列元素處理結果為False時候開始迭代seq後所有的值 輸出:[1, 2, 10, 11]
def dropwhileTest():
print(list(itertools.dropwhile(lambda x: x > 6, [8, 9, 1, 2, 10, 11])))
## filterfalse(pred,seq) 當pred處理為假的元素 輸出:[1, 2]
def filterfalseTest():
print(list(itertools.filterfalse(lambda x: x > 6, [8, 9, 1, 2, 10, 11])))
## takewhile 與dropwhile相反 當pred對序列元素處理結果為True時候開始迭代seq後所有的值 輸出:[8, 9]
def takewhileTest():
print(list(itertools.takewhile(lambda x: x > 6, [8, 9, 1, 2, 10, 11])))
## tee(it, n) 將it重復n次進行迭代
def teeTest():
for its in itertools.tee([0, 1], 2):
for it in its:
print(it)
## zip_longest(p,q,...) 按每個序列中對應位置元素組合成新的元素進行迭代
def zip_longestTest():
for i in itertools.zip_longest([1, 2, 3, 8], [3, 4, 5, 76], (0, 2, 3, 4)):
print(i)
## product(p,q,...[,n]) 迭代排列中出現元素的全排列
def productTest():
for i in itertools.product([1, 2, 3, 8], [3, 4, 5, 76]):
print(i)
## permutations(p, q) 求p迭代序列中q個元素的全排列
def permutationsTest():
print(list(itertools.permutations([1, 2, 3, 4], 4)))
print(list(itertools.permutations('ASBD', 4)))
## combinations(p, r)迭代序列中r個元素的組合
def combinationsTest():
print(list(itertools.combinations('abc', 2)))
print(list(itertools.combinations([1, 2, 3], 2)))
if __name__ == '__main__':
combinationsTest()

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved