提取字典的子集

2021-10-04 00:19:49 字數 541 閱讀 6232

有時候,需要根據已知的字典物件構造乙個新的字典物件。這種場景可以使用字典生成式(dictionary comprehension)。如下:

prices = 

# make a dictionary of all prices over 200

p1 =

# make a dictionary of tech stocks

tech_names =

p2 =

同樣,也可以使用dict的建構函式,如下:

p1 = dict((key, value) for key, value in prices.items() if value > 200)
然而,使用字典生成式更清晰,實際執行速度要快得多(在示例中使用的字典上測試時速度快兩倍)。

下面是另一種示例:

# make a dictionary of tech stocks

tech_names =

p2 =

提取字典的子集

有時候,需要根據已知的字典物件構造乙個新的字典物件。這種場景可以使用字典生成式 dictionary comprehension 如下 prices make a dictionary of all prices over 200 p1 make a dictionary of tech stock...

python程式設計技巧之從字典中提取子集

首先我們會想到使用字典推導式 dictionary comprehension 來解決這個問題,例如以下場景 選出 大於 200 的 gt200 print gt200 print 提取科技公司的相關資訊 techdict print techdict 執行結果如下 大部分可以通過字典推導式解決的問...

pcl 提取子集(平面)

在點雲裡提取了一些子集 平面 並顯示出來 參考鏈結 include include include include include include include include include include include include int main int argc,char argv ...