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

Learn Python from master up Turtle - Part 2

編輯:Python

all() & any() all() Determine whether the values of all elements in the iteratable object are true ,any() Determine whether there is an element in the iteratable object that is true .

>>> x = [1, 0, 2]
>>> y = [1, 1, 9]
>>> all x
SyntaxError: invalid syntax
>>> all(x)
False
>>> all(y)
True
>>> any(x)
True

enumerate() Function is used to return an enumerated object , The function is to iterate every element in the object and from 0 The starting sequence numbers together form a list of two tuples .

>>> seasons = ["Spring", "Summer", "Fall", "Winter"]
>>> enumerate(seasons)
<enumerate object at 0x0000020F53FA4D80>
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, 10))
[(10, 'Spring'), (11, 'Summer'), (12, 'Fall'), (13, 'Winter')]

zip() Function is used to create an iterator that aggregates multiple iteratable objects , It will successively combine each element of each iteratable object passed in as a parameter into a meta group , That is to say i Tuples contain the... From each parameter i Elements .

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
>>> z = [7, 8, 9]
>>> zipped = zip(x, y, z)
>>> list(zipped)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

If the length is inconsistent , Select the shortest iteratible object to terminate , The rest is abandoned
>>> z = "FishC"    
>>> zipped = zip(x, y, z)
>>> list(zipped)
[(1, 4, 'F'), (2, 5, 'i'), (3, 6, 's')]

If you don't want to discard , Can be introduced itertools Module zip_longest() function , No use None completion
>>> import itertools
>>> zipped = itertools.zip_longest(x, y, z)
>>> list(zipped)
[(1, 4, 'F'), (2, 5, 'i'), (3, 6, 's'), (None, None, 'h'), (None, None, 'C')] 

map() The function performs operations on each element of the specified iteratable object according to the provided function , And will return the iterator of the operation result .ord The function converts a string to a corresponding encoded value ,pow A function is a function of power . If the length is different , This operation ends when the shortest iteratible object terminates .

>>> mapped = map(ord, "FishC")
>>> list(mapped)
[70, 105, 115, 104, 67]
>>> mapped = map(pow, [3, 4, 6], [2, 1, 5])
>>> list(mapped)
[9, 4, 7776]
>>> mapped = map(pow, [2, 3, 10], [5, 2, 3])
>>> list(mapped)
[32, 9, 1000]

filter() The function performs operations on each element of the specified iteratable object according to the provided function , And the result of the operation is a positive element , Returns... As an iterator .

>>> list(filter(str.islower, "FishC"))
['i', 's', 'h']


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