三元表達式,列表推導式,生成器表達式

三元表達式

為真時的結果 if 判定條件 else 為假時的結果 

name=input('姓名>>: ')
res='SB' if name == 'alex' else 'NB'
print(res)

列表推導式

#1、示例
egg_list=[]
for i in range(10):
    egg_list.append('雞蛋%s' %i)

egg_list=['雞蛋%s' %i for i in range(10)]

#2、語法

[expression for item1 in iterable1 if condition1
for item2 in iterable2 if condition2
...
for itemN in iterableN if conditionN
]
類似于
res=[]
for item1 in iterable1:
    if condition1:
        for item2 in iterable2:
            if condition2
                ...
                for itemN in iterableN:
                    if conditionN:
                        res.append(expression)

#3、優(yōu)點:方便,改變了編程習慣,可稱之為聲明式編程

生成器表達式

1、把列表推導式的[]換成()就是生成器表達式
2、示例:把之前生一筐雞蛋變成你一只老母雞,用的時候就下蛋,這就是生成器特性。
3、優(yōu)點:省內存,一次只產生一個值在內存中、

匿名函數(shù)

匿名就是沒有名字
def func(x,y,z=1):
    return x+y+z

匿名
lambda x,y,z=1:x+y+z #與函數(shù)有相同的作用域,但是匿名意味著引用計數(shù)為0,使用一次就釋放,除非讓其有名字
func=lambda x,y,z=1:x+y+z 
func(1,2,3)
#讓其有名字就沒有意義

有名字的函數(shù)和匿名函數(shù)的對比

有名函數(shù):循環(huán)使用,保存了名字,通過名字就可以重復引用函數(shù)功能
匿名函數(shù):一次性使用,隨時隨地定義

##內置函數(shù)
注意:內置函數(shù)id()可以返回一個對象的身份,返回值為整數(shù)。這個整數(shù)通常對應與該對象在內存中的位置。
######is 運算符用于比較兩個對象的身份,等號比較兩個對象的值,內置函數(shù)type()則返回一個對象的類型。
參考文獻:
http://www.cnblogs.com/linhaifeng/articles/7580830.html

##給匿名函數(shù)加buff

#相關官網鏈接:
https://docs.python.org/3/library/functions.html#filter

######map函數(shù)
map函數(shù)會對列表中的所有元素進行操作,map有兩個參數(shù)(函數(shù),列表),他會在內部遍歷列表中的每一個元素,執(zhí)行傳遞過來的函數(shù)參數(shù)。再輸入到新列表中。

1 li = [11, 22, 33]
2 new_list = map(lambda a: a + 100, li)
輸出:[111, 122, 133]

######reduce函數(shù)
reduce函數(shù)會對于序列內元素進行累計操作
Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value.

For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the sequence. If the optional initializer is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty. If initializer is not given and sequence contains only one item, the first item is returned.

reduce用法鏈接:https://docs.python.org/3/library/functools.html#functools.reduce

######filter函數(shù)
filter函數(shù),可以根據(jù)條件對數(shù)據(jù)進行過濾

li = [1,2,3,4,5,6]
new_li = filter(lambda i:i>2,li)
print(list(new_li))


最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容