鮮為人知的python5種高級特征

任何編程語言的高級特征通常都是通過大量的使用經(jīng)驗才發(fā)現(xiàn)的。比如你在編寫一個復(fù)雜的項目,并在 stackoverflow 上尋找某個問題的答案。然后你突然發(fā)現(xiàn)了一個非常優(yōu)雅的解決方案,它使用了你從不知道的 Python 功能!

Lambda 函數(shù)
Lambda 函數(shù)是一種比較小的匿名函數(shù)——匿名是指它實際上沒有函數(shù)名。
Python 函數(shù)通常使用 def a_function_name() 樣式來定義,但對于 lambda 函數(shù),我們根本沒為它命名。這是因為 lambda 函數(shù)的功能是執(zhí)行某種簡單的表達式或運算,而無需完全定義函數(shù)。
lambda 函數(shù)可以使用任意數(shù)量的參數(shù),但表達式只能有一個。
x = lambda a, b : a * b
print(x(5, 6)) # prints 30
x = lambda a : a*3 + 3
print(x(3)) # prints 12
Map 函數(shù)
def square_it_func(a):
return a * a
x = map(square_it_func, [1, 4, 7])
print(x) # prints [1, 16, 47]
def multiplier_func(a, b):
return a * b
x = map(multiplier_func, [1, 4, 7], [2, 5, 8])
print(x) # prints [2, 20, 56] 看看上面的示例!我們可以將函數(shù)應(yīng)用于單個或多個列表。實際上,你可以使用任何 Python 函數(shù)作為 map 函數(shù)的輸入,只要它與你正在操作的序列元素是兼容的。
Filter 函數(shù)
# Our numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
# Function that filters out all numbers which are odd
def filter_odd_numbers(num):
if num % 2 == 0:
return True
else:
return False
filtered_numbers = filter(filter_odd_numbers, numbers)
print(filtered_numbers)
# filtered_numbers = [2, 4, 6, 8, 10, 12, 14]
Itertools 模塊
from itertools import *
# Easy joining of two lists into a list of tuples
for i in izip([1, 2, 3], [ a , b , c ]):
print i
# ( a , 1)
# ( b , 2)
# ( c , 3)
# The count() function returns an interator that
# produces consecutive integers, forever. This
# one is great for adding indices next to your list
# elements for readability and convenience
for i in izip(count(1), [ Bob , Emily , Joe ]):
print i
# (1, Bob )
# (2, Emily )
# (3, Joe )
# The dropwhile() function returns an iterator that returns
# all the elements of the input which come after a certain
# condition becomes false for the first time.
def check_for_drop(x):
print Checking: , x
return (x > 5)
for i in dropwhile(should_drop, [2, 4, 6, 8, 10, 12]):
print Result: , i
# Checking: 2
# Checking: 4
# Result: 6
# Result: 8
# Result: 10
# Result: 12
# The groupby() function is great for retrieving bunches
# of iterator elements which are the same or have similar
# properties
a = sorted([1, 2, 1, 3, 2, 1, 2, 3, 4, 5])
for key, value in groupby(a):
print(key, value), end= )
# (1, [1, 1, 1])
# (2, [2, 2, 2])
# (3, [3, 3])
# (4, [4])
# (5, [5])
Generator 函數(shù)
# (1) Using a for loopv
numbers = list()
for i in range(1000):
numbers.append(i+1)
total = sum(numbers)
# (2) Using a generator
def generate_numbers(n):
num, numbers = 1, []
while num < n:
numbers.append(num)
num += 1
return numbers
total = sum(generate_numbers(1000))
# (3) range() vs xrange()
total = sum(range(1000 + 1))
total = sum(xrange(1000 + 1))
(版權(quán)歸原作者所有,侵刪)
![]()

點擊下方“閱讀原文”查看更多
評論
圖片
表情
