python例項 元組命名 頻次統計 字典排序

2022-04-03 19:54:40 字數 1885 閱讀 6943

1.為元組中元素命名

方法1.定義常量

name, age = 0, 1

student = ('

喬峰', 29, '

[email protected]')

name =student[name]

age = student[age]

方法2.使用 namedtuple

from collections import

namedtuple

student = namedtuple('

student

', ['

name

', '

age', '

email'])

stu = student('

喬峰', 29, '

[email protected]')

name =stu.name

age =stu.age

2. 統計陣列元素頻次

方法1. 生成字典統計

lis = [8, 9, 9, 9, 9, 2, 10, 0, 7, 6, 2, 5, 1, 5, 0, 10, 8, 4, 1, 1, 6, 5, 10, 7, 9, 3, 2, 5, 3, 10]

# 生成字典 鍵 = 陣列元素,值 = 0

d = dict.fromkeys(lis, 0) #

# 遍歷陣列,統計頻次

for x in

lis:

d[x] += 1

print(d) #

方法2. 使用counter

from collections import

counter

lis = [8, 9, 9, 9, 9, 2, 10, 0, 7, 6, 2, 5, 1, 5, 0, 10, 8, 4, 1, 1, 6, 5, 10, 7, 9, 3, 2, 5, 3, 10]

ret =counter(lis)

print(ret) #

#出現頻次最高的項

top = ret.most_common(3)

print(top) # [(9, 5), (10, 4), (5, 4)]

3.按字典值排序

方法1 使用元組

score = 

# 根據字典的值,鍵,生成元組

score_tup =zip(score.values(), score.keys()) # 生成元組 (72, 'a'), (97, 'b'), (81, 'c'), (75, 'x'), (84, 'y'), (93, 'z')

# 排序

sorted_score =sorted(score_tup)

print(sorted_score) # [(72, 'a'), (75, 'x'), (81, 'c'), (84, 'y'), (93, 'z'), (97, 'b')]

方法2 使用 sorted 的key

score = 

# score.items = dict_items([('a', 72), ('b', 97), ('c', 81), ('x', 75), ('y', 84), ('z', 93)])

# 用 lambda 引數中 x 的第一項排序。(第0項是 "a", 第一項是 72)

sorted_score = sorted(score.items(), key = lambda x: x[1])

print(sorted_score) # ('a', 72), ('x', 75), ('c', 81), ('y', 84), ('z', 93), ('b', 97)

python例項 元組命名 頻次統計 字典排序

1.為元組中元素命名 方法1.定義常量 name,age 0,1 student 喬峰 29,qf jinyong.com name student name age student age 方法2.使用 namedtuple from collections import namedtuple s...

Python命名元組 namedtuple

python中提供了基礎的不可變資料結構元組tuple,對元組元素的訪問需通過索引來完成,對此需要熟記每個下標對應的具體含義。如果元素數量一多,要記清楚這些東西就會比較麻煩了,於是就出現了命名元組namedtuple。collections.namedtuple point x y 這樣就建立了乙個...

python中命名元組

實際上 collections.namedtuple 是乙個工廠方法,它返回的是python中標準元組型別的子類。我們提供給它乙個型別名稱以及相應的字段,它就返回乙個可例項化的類為你已經定義好的字段傳入值等。from collections import namedtuple subscriber ...