List類系列(一) list中各元素出現的次數

2021-10-07 14:01:43 字數 1103 閱讀 5285

**如下:

from collections import counter

a = [1, 2, 3, 1, 1, 2]

result = counter(a)

print(result)

collections這個模組實現了特定目標的容器,以提供python標準內建容器 dict、list、set、tuple 的替代選擇。

一、安裝

二、常用類及方法

1.所有類

2.counter類

counter是dict乙個子類,主要用來對訪問物件的頻率進行計數。

常用方法:

elements():返回乙個迭代器,每個元素重複計算的個數,如果乙個元素的計數小於1,就會被忽略。

most_common([n]):返回乙個列表,提供n個訪問頻率最高的元素和計數

1)統計各元素出現的次數

a = [1, 2, 3, 1, 1, 2]

result = counter(a)

2)獲取指定物件的訪問次數

1_count = result["1"]
3)檢視元素

>>> list(result.elements())

['1', '2', '3']

4)追加物件

>>> c = collections.counter('hello world hello world hello nihao'.split())

>>> d = collections.counter('hello world'.split())

>>> c

counter()

>>> d

counter()

>>> c + d

counter()

5)減少物件

>>> c - d

counter()

6)清除

>>> c.clear()

>>> c

counter()

List類系列(二) List類的list 方法

1.用於將元組轉換為列表 元組與列表是非常類似的,區別在於元組的元素值不能修改,元組是放在括號中,列表是放於方括號中。以下例項展示了 list 函式的使用方法 usr bin python coding utf 8 atuple 123,xyz zara abc alist list atuple ...

java 集合類List系列 二

現討論一下以下的問題 如果需要刪除 重複的元素那該如何處理?list.add new student 張三 23 list.add new student 張三 23 list.add new student 李四 24 list.add new student 張三 23 list.add new...

Java中list類的使用

1 arraylist為list的重要實現類,list中的元素是有序排列並且可重複的。list的建立 list list new arraylist 2 list的方法 list中元素個數是否為空?list.isempty list是否已經被建立 null list 獲取list的長度 list.s...