Python 集合


在 Python 中,集合是用於儲存資料的容器。Python 中的內建資料結構包括元組、列表、集合和字典。collections 類除了內建資料結構外,還提供了其他資料結構。

‘collections’ 模組中的一些資料結構:

  • Counter

  • namedTuple

  • orderedDict

  • defaultDict

  • Deque

  • chainMap

Counter

它是一種集合型別,其中元素將儲存為字典鍵,計數將儲存為字典值。

當您想要計算列表中任何專案的頻率時,傳統上您會使用一個名為“count”的變數,該變數最初設定為零,並且每次遇到該專案時都會遞增 1。當列表很長時,這不是一種最佳化的方法。因此,為了防止這種情況並在同一時間計算不同的物件,我們將使用計數器。

示例

在下面的示例中,從 collections 庫匯入 Counter 方法。然後建立一個名為 'a' 的字串並將其賦值為“tutorialspoint”。

from collections import Counter
a="tutorialspoint"
result=Counter(a)
print(result)

輸出

執行上述程式後,它會打印出 'a' 中每個字母的字典,以及每個字母出現的次數。

Counter({'t': 3, 'o': 2, 'i': 2, 'u': 1, 'r': 1, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1

values() 函式

values() 函式將返回與所有值關聯的計數列表。

示例

from collections import Counter
a=["apple","mango","cherry","apple","mango","mango"]
result=Counter(a)
print(result.values())

輸出

dict_values([2, 3, 1])

most_common() 函式

most_common() 函式用於返回具有最大計數的專案/專案的字典。需要顯示的值的數量必須在括號內指定。

示例

from collections import Counter
a=["apple","mango","cherry","apple","mango","mango"]
result=Counter(a)
print(result.most_common(1))
print(result.most_common(2))

輸出

[('mango', 3)]
[('mango', 3), ('apple', 2)]

namedtuple() 函式

namedtuple() 允許我們建立具有命名欄位的元組。因此,我們可以使用點表示法訪問它們,而不是使用索引訪問它們。

使用索引訪問元組的專案可能很困難且令人困惑。為了防止這種情況,我們可以使用namedtuple()。

與元組一樣,namedtuple 也是不可變的。

namedtuple 接受兩個引數。

示例

在下面的示例中,此程式建立了一個名為“person”的 namedtuple,它具有四個欄位:name、place、sex 和 age。然後,它建立了一個名為 id 的 person namedtuple 的例項,併為每個欄位提供值。

from collections import namedtuple
person=namedtuple("person",["name","place","sex","age"])
id=person("kavya","Hyderabad","F","21")
print(id[1])
print(id[3])
print(id.place)
print(id.age)

輸出

Hyderabad
21
Hyderabad
21

OrderedDict

OrderedDict 是一種可以記住其專案順序的字典。它用於保留將專案新增到列表中的順序。可以以類似於普通字典的各種方式將專案新增到 OrderedDict 中。

示例

from collections import OrderedDict
d=OrderedDict()
d['sachin']=100
d['Dhoni']=90
d['Rohit']=110
d['Kohli']=95
print(d)

輸出

執行上述程式碼後,它會生成以下程式並列印整個字典。

OrderedDict([('sachin', 100), ('Dhoni', 90), ('Rohit', 110), ('Kohli', 95)])

示例

以下程式從 collections 模組匯入 OrderedDict 類,並建立一個具有四個鍵值對的 OrderedDict 物件。鍵為 'sachin'、'Dhoni'、'Rohit' 和 'Kohli'。值分別為 100、90、110 和 95。

from collections import OrderedDict
d=OrderedDict([('sachin',100),('Dhoni',90),('Rohit',110),('Kohli',95)])
print(d)
print(d.keys())

輸出

OrderedDict([('sachin', 100), ('Dhoni', 90), ('Rohit', 110), ('Kohli', 95)])
odict_keys(['sachin', 'Dhoni', 'Rohit', 'Kohli'])

defaultdict

defaultdict 具有字典的所有功能,並具有一個附加功能,即它永遠不會引發 KeyError。在字典中,如果您嘗試訪問或修改不存在的鍵,則會得到 KeyError。而 defaultdict 在鍵不存在時始終分配一個預設值。因此,defaultdict 用於處理缺失的鍵。

示例

以下程式從 collections 模組匯入 defaultdict 類。然後,它使用 defaultdict 建立一個新的字典 d,並將其設定為接收整數值。三個鍵值對被新增到字典中,'Sachin' 的值為 90,'Dhoni' 的值為 80,'Virat' 的值為 95。

from collections import defaultdict
d=defaultdict(int)
d['Sachin']=90
d['Dhoni']=80
d['Virat']=95
print(d)
print(d['Dhoni'])
print(d['Rohit'])

輸出

defaultdict(, {'Sachin': 90, 'Dhoni': 80, 'Virat': 95})
80
0

由於 'Rohit' 未定義且 'int' 作為引數給出,因此預設值為 0。

示例

from collections import defaultdict
d=defaultdict(float)
d['Sachin']=90
d['Dhoni']=80
print(d['Rohit'])

輸出

0.0

更新於: 2023年4月24日

3K+ 閱讀量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告