新聞中心
Python 推導(dǎo)式
Python 推導(dǎo)式是一種獨特的數(shù)據(jù)處理方式,可以從一個數(shù)據(jù)序列構(gòu)建另一個新的數(shù)據(jù)序列的結(jié)構(gòu)體。

賓川ssl適用于網(wǎng)站、小程序/APP、API接口等需要進行數(shù)據(jù)傳輸應(yīng)用場景,ssl證書未來市場廣闊!成為成都創(chuàng)新互聯(lián)的ssl證書銷售渠道,可以享受市場價格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:18980820575(備注:SSL證書合作)期待與您的合作!
Python 支持各種數(shù)據(jù)結(jié)構(gòu)的推導(dǎo)式:
- 列表(list)推導(dǎo)式
- 字典(dict)推導(dǎo)式
- 集合(set)推導(dǎo)式
- 元組(tuple)推導(dǎo)式
列表推導(dǎo)式
列表推導(dǎo)式格式為:
[表達式 for 變量 in 列表] [out_exp_res for out_exp in input_list] 或者 [表達式 for 變量 in 列表 if 條件] [out_exp_res for out_exp in input_list if condition]
- out_exp_res:列表生成元素表達式,可以是有返回值的函數(shù)。
- for out_exp in input_list:迭代 input_list 將 out_exp 傳入到 out_exp_res 表達式中。
- if condition:條件語句,可以過濾列表中不符合條件的值。
過濾掉長度小于或等于3的字符串列表,并將剩下的轉(zhuǎn)換成大寫字母:
實例
>>> names
=
[
'Bob'
,
'Tom'
,
'alice'
,
'Jerry'
,
'Wendy'
,
'Smith'
]
>>> new_names
=
[name.
upper
(
)
for name
in names
if
len
(name
)
>
3
]
>>>
print
(new_names
)
[
'ALICE'
,
'JERRY'
,
'WENDY'
,
'SMITH'
]
計算 30 以內(nèi)可以被 3 整除的整數(shù):
實例
>>> multiples
=
[i
for i
in
range
(
30
)
if i %
3
==
0
]
>>>
print
(multiples
)
[
0
,
3
,
6
,
9
,
12
,
15
,
18
,
21
,
24
,
27
]
字典推導(dǎo)式
字典推導(dǎo)基本格式:
{ key_expr: value_expr for value in collection }
或
{ key_expr: value_expr for value in collection if condition }使用字符串及其長度創(chuàng)建字典:
實例
listdemo
=
[
'Google'
,
'Runoob'
,
'Taobao'
]
# 將列表中各字符串值為鍵,各字符串的長度為值,組成鍵值對
>>> newdict
=
{key:
len
(key
)
for key
in listdemo
}
>>> newdict
{
'Google':
6
,
'Runoob':
6
,
'Taobao':
6
}
提供三個數(shù)字,以三個數(shù)字為鍵,三個數(shù)字的平方為值來創(chuàng)建字典:
實例
>>> dic
=
{x: x**
2
for x
in
(
2
,
4
,
6
)
}
>>> dic
{
2:
4
,
4:
16
,
6:
36
}
>>>
type
(dic
)
<
class
'dict'
>
集合推導(dǎo)式
集合推導(dǎo)式基本格式:
{ expression for item in Sequence }
或
{ expression for item in Sequence if conditional }計算數(shù)字 1,2,3 的平方數(shù):
實例
>>> setnew
=
{i**
2
for i
in
(
1
,
2
,
3
)
}
>>> setnew
{
1
,
4
,
9
}
判斷不是 abc 的字母并輸出:
實例
>>> a
=
{x
for x
in
'abracadabra'
if x
not
in
'abc'
}
>>> a
{
'd'
,
'r'
}
>>>
type
(a
)
<
class
'set'
>
元組推導(dǎo)式(生成器表達式)
元組推導(dǎo)式可以利用 range 區(qū)間、元組、列表、字典和集合等數(shù)據(jù)類型,快速生成一個滿足指定需求的元組。
元組推導(dǎo)式基本格式:
(expression for item in Sequence ) 或 (expression for item in Sequence if conditional )
元組推導(dǎo)式和列表推導(dǎo)式的用法也完全相同,只是元組推導(dǎo)式是用 () 圓括號將各部分括起來,而列表推導(dǎo)式用的是中括號 [],另外元組推導(dǎo)式返回的結(jié)果是一個生成器對象。
例如,我們可以使用下面的代碼生成一個包含數(shù)字 1~9 的元組:
實例
>>> a
=
(x
for x
in
range
(
1
,
10
)
)
>>> a
0x7faf6ee20a50
>
# 返回的是生成器對象
>>>
tuple
(a
)
# 使用 tuple() 函數(shù),可以直接將生成器對象轉(zhuǎn)換成元組
(
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
)
分享標(biāo)題:Python 推導(dǎo)式
本文地址:http://fisionsoft.com.cn/article/dhpphpd.html


咨詢
建站咨詢
