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

Python comprehension, inclusion, iterators

編輯:Python

Python語法–Derivation or contain

  • list comprehensionOperating a sequence types of data sets can be deduced another sequence types of data sets:
  1. 典型的情況:
for i in aiterator
  1. Using the derived to obtain a list of square number
square = [i * i for i in range(1, 11)]
  • The above situation with the following cycle
for i in range(1, 11):
square.append(i * i)
  1. A dictionary is grammar the following format:
{
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. 使用ifStatements for choosing traversal elements,The following rules of grammar:
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]
##Only take the age
infoMap_odd = {
k: v for k, v in zip(keys, values) if k == 'age'}
##Through the dictionary to generate a dictionary
dict_one = {
'name': 'jiamin', 'age': '28', 'weight': '81'}
dict_two = {
k: v for k, v in dict_one.items() if k == 'name'}

python中迭代器

  • 迭代器是PythonA data object in the container,When to use each time from one out,直到取完
自定義迭代器
  • As long as defining a realization method of the iterator protocol classes can be,Main agreement method and two admission
__iter__() ## Way back into the object itself,他是for語句使用迭代器的要求
__next__() ## The next element method returns the container or data,When the container data out of,應該引發StopIteration
  • Custom iterator code is as follows:
## Custom generation device through
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)
內置迭代器工具
  • PythonBuilt a used to generate the iterator functioniter(),Another standard libraryitertoolsModule and rich iterator tools:
  • A built-in iterator instance:
## Built-in iterators iterate through
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("Built-in iterators iterate through: ", i)
itertoolsTool is commonly used in module function
import itertools
## 迭代器工具類
## 從1 開始,This to each3 For iteration
def countTest():
for i in itertools.count(1, 3):
print(i)
if i >= 10:
break
##Wireless loop iteration
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,...)Link iteration,將p,qConnect the iterative output:[1, 2, 3, 4, 5, 6]
def chainTest():
print(list(itertools.chain([1, 2, 3], [4, 5, 6])))
## compress(data,selectors) 根據selectorsThe values in the iterationdataIn a sequence of values 輸出: [1, 3]
def compressTest():
print(list(itertools.compress([1, 2, 3, 4], [1, None, True, False])))
## dropwhile(pred,seq) 當predThe result of the processing sequence elements asFalseTime to start the iterationseqAfter all the value of the 輸出:[1, 2, 10, 11]
def dropwhileTest():
print(list(itertools.dropwhile(lambda x: x > 6, [8, 9, 1, 2, 10, 11])))
## filterfalse(pred,seq) 當predDealing with false elements 輸出:[1, 2]
def filterfalseTest():
print(list(itertools.filterfalse(lambda x: x > 6, [8, 9, 1, 2, 10, 11])))
## takewhile 與dropwhile相反 當predThe result of the processing sequence elements asTrueTime to start the iterationseqAfter all the value of the 輸出:[8, 9]
def takewhileTest():
print(list(itertools.takewhile(lambda x: x > 6, [8, 9, 1, 2, 10, 11])))
## tee(it, n) 將it重復nIterate times
def teeTest():
for its in itertools.tee([0, 1], 2):
for it in its:
print(it)
## zip_longest(p,q,...) According to the corresponding position elements in each sequence combined into new elements to iterate
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]) Iterative arrangement of elements of the whole arrangement
def productTest():
for i in itertools.product([1, 2, 3, 8], [3, 4, 5, 76]):
print(i)
## permutations(p, q) 求pIterative sequence ofq個元素的全排列
def permutationsTest():
print(list(itertools.permutations([1, 2, 3, 4], 4)))
print(list(itertools.permutations('ASBD', 4)))
## combinations(p, r)Iterative sequence ofr個元素的組合
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