說明
- 在
裡對集合進行流處理并生成新的集合可以使用Python
内置函數。它和map
的Java
的Stream
方法的作用是一樣的,都是對集合内的每個元素修改。map()
-
函數傳回一個map()
, 它的第一個參數是函數或者iterator
函數,用來周遊每個元素的,而第二個和之後的參數是可枚舉對象,比如元組,清單,序列等。如果有多個可枚舉對象,那麼哪個先結束,其他的也會終止。lambda
例子
def TestBuildInMap():
rows = ["csdn","infoworld","blog","wtl","c++11"]
# 注意,map的lambda調用時惰性的,隻有在讀取這個iterator的值時才會調用。
ite = map(lambda row: (print("->"),{"name": row}),rows)
# 使用for-in枚舉
print("use for-in...")
for one in ite:
print(one)
# 使用next()函數
print("use next()..")
ite = map(lambda row: {"value": row},rows)
try:
one = next(ite)
while one:
print(one)
one = next(ite)
except StopIteration as e:
print(e)
# 建立list
value = list(map(lambda row: {"key": row},rows))
print(value)
pass
if __name__ == '__main__':
print("hello world!")
TestBuildInMap()
輸出
hello world!
use for-in...
->
(None, {'name': 'csdn'})
->
(None, {'name': 'infoworld'})
->
(None, {'name': 'blog'})
->
(None, {'name': 'wtl'})
->
(None, {'name': 'c++11'})
use next()..
{'value': 'csdn'}
{'value': 'infoworld'}
{'value': 'blog'}
{'value': 'wtl'}
{'value': 'c++11'}
[{'key': 'csdn'}, {'key': 'infoworld'}, {'key': 'blog'}, {'key': 'wtl'}, {'key': 'c++11'}]
參考
- Built-in Functions