日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python中對字典的幾個處理方法分享_python

作者:data大柳 ? 更新時間: 2022-10-27 編程語言

字典求和

edge_weights = defaultdict(lambda: defaultdict(float))
for idx,node in enumerate(graph.nodes()):
    node2com[node] = idx    #給每一個節點初始化賦值一個團id
    for edge in graph[node].items():
        edge_weights[node][edge[0]] = edge[1]['weight']

edge_weights

運行結果:

defaultdict(<function __main__.<lambda>()>,
? ? ? ? ? ? {'397564': defaultdict(float,
? ? ? ? ? ? ? ? ? ? ? ? ?{'15.1.18010.11898': 71,
? ? ? ? ? ? ? ? ? ? ? ? ? '15.1.18010.11899': 54,
? ? ? ? ? ? ? ? ? ? ? ? ? '15.1.18009.11899': 75,
? ? ? ? ? ? ? ? ? ? ? ? ? '15.1.18009.11898': 160}),
? ? ? ? ? ? ?'15.1.18010.11898': defaultdict(float,
? ? ? ? ? ? ? ? ? ? ? ? ?{'397564': 71,
? ? ? ? ? ? ? ? ? ? ? ? ? '577806': 61,
? ? ? ? ? ? ? ? ? ? ? ? ? '73827465': 66,
? ? ? ? ? ? ? ? ? ? ? ? ? '30009791666': 62,
? ? ? ? ? ? ? ? ? ? ? ? ? '30005407392': 59,
? ? ? ? ? ? ? ? ? ? ? ? ? '100293225': 102,
? ? ? ? ? ? ? ? ? ? ? ? ? '30012147301': 65,
? ? ? ? ? ? ? ? ? ? ? ? ? '138661946': 52}),
? ? ? ? ? ? ?'1085941': defaultdict(float,
? ? ? ? ? ? ? ? ? ? ? ? ?{'15.1.18007.11870': 120,
? ? ? ? ? ? ? ? ? ? ? ? ? '15.1.18005.11872': 55,
? ? ? ? ? ? ? ? ? ? ? ? ? '15.1.18004.11872': 75,
? ? ? ? ? ? ? ? ? ? ? ? ? '15.1.18006.11870': 83,
? ? ? ? ? ? ? ? ? ? ? ? ? '15.1.18004.11871': 63})
})

對上述edge_weights所有的值匯入列表并求和:

sum(
    [weight for start in edge_weights.keys() for end, weight in edge_weights[start].items()]
)

列表剔重并計數

方法1:

統計列表中的重復項出現的次數。
循環遍歷出一個可迭代對象中的元素,如果字典沒有該元素,那么就讓該元素作為字典的鍵,并將該鍵賦值為1,如果存在就將該元素對應的值加1.

lists = ['a','a','b',5,6,7,5,'a']
count_dict = dict()

for item in lists:
    if item in count_dict:
        count_dict[item] += 1
    else:
        count_dict[item] = 1

方法2:

使用collections.defaultdict(),將default_factory設為int,代碼如下:

from collections import defaultdict
#s = 'mississippi'
s = ['a','a','b',5,6,7,5,'a']
d = defaultdict(int)
for k in s:
    d[k] += 1
print('\n',d)

獲取字典中最大的value

a = {'a':2,'b':3,'c':5,'d':9,'e':4}
print(max(a.values()))

獲取字典中出現value最大的key

a = {'a':2,'b':3,'c':5,'d':9,'e':4}
print(max(a,key=a.get))

運行結果:

d

字典對應元素追加

對于列表:

s = [('yellow',1),('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]

統計列表字典有兩種方法:

方法1:

用dict.setdefault()實現。

代碼如下:

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = {}
for k, v in s:
    d.setdefault(k,[]).append(v)
a = sorted(d.items())
print(a)

運行結果:

[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

方法2;

使用collections.defaultdict(),并使用list作第一個參數,可以很容易將鍵-值對序列轉換為列表字典,

代碼如下:

from collections import defaultdict
s = [('yellow',1),('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)
for k, v in s:
    d[k].append(v)
a = sorted(d.items())
print(a)

運行結果:

[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

當字典中沒有的鍵第一次出現時,default_factory自動為其返回一個空列表,list.append()會將值添加進新列表;再次遇到相同的鍵時,list.append()將其它值再添加進該列表。這種方法比使用dict.setdefault()更為便捷。

字典對應元素追加并剃重

對于列表:

s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]

統計并剃重:

from collections import defaultdict
s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
d = defaultdict(set)
for k, v in s:
    d[k].add(v)
print('\n',d)

運行結果:

defaultdict(<class 'set'>, {'red': {1, 3}, 'blue': {2, 4}})

對字典進行過濾

創建一個新的字典,可以利用字典推導式

headerTable = {k: v for k, v in headerTable.items() if v > 2}

反轉字典的方法(字典的key和value對換)

使用字典推導:

m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
{v: k for k, v in m.items()}

使用壓縮器:

m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
m.items()    #[('a', 1), ('c', 3), ('b', 2), ('d', 4)]
zip(m.values(), m.keys())   #[(1, 'a'), (3, 'c'), (2, 'b'), (4, 'd')]
mi = dict(zip(m.values(), m.keys()))

字典的key和value對換并把key按照value進行列表合并

對于字典:

defaultdict(int,
            {'2100201919459568780': 0,
             '2100201927433498080': 1,
             '2100201935997972401': 2,
             '2100201934073343294': 3,
             '2100201938073398590': 3,
             '2100201938426179130': 2,
             '2100201938057211020': 4,
             '2100201938030472762': 3,
             '2100201940356247098': 4,
             '2100201939150253460': 4,
             '2100201935737728404': 4,
             '2100201938984381844': 4,
             '2100201937770425806': 4,
             '2100201937563397283': 4,
             '2100201941426286415': 4,
             '2100201936062819790': 4,
             '2100201936279351185': 4,
             '2100201934074097553': 4,
             '2100201940543713169': 4})

進行處理:

track_merge = defaultdict(list)
for i in track_label.items():
    track_merge[str(i[1])].append(i[0])

輸出:

defaultdict(list,
? ? ? ? ? ? {'0': ['2100201919459568780'],
? ? ? ? ? ? ?'1': ['2100201927433498080'],
? ? ? ? ? ? ?'2': ['2100201935997972401', '2100201938426179130'],
? ? ? ? ? ? ?'3': ['2100201934073343294',
? ? ? ? ? ? ? '2100201938073398590',
? ? ? ? ? ? ? '2100201938030472762'],
? ? ? ? ? ? ?'4': ['2100201938057211020',
? ? ? ? ? ? ? '2100201940356247098',
? ? ? ? ? ? ? '2100201939150253460',
? ? ? ? ? ? ? '2100201935737728404',
? ? ? ? ? ? ? '2100201938984381844',
? ? ? ? ? ? ? '2100201937770425806',
? ? ? ? ? ? ? '2100201937563397283',
? ? ? ? ? ? ? '2100201941426286415',
? ? ? ? ? ? ? '2100201936062819790',
? ? ? ? ? ? ? '2100201936279351185',
? ? ? ? ? ? ? '2100201934074097553',
? ? ? ? ? ? ? '2100201940543713169']})

合并字典

appointment = { 'soccer' : { 'day': 20, 'month': 'april' } }
appointment2 = { 'gym' : { 'day': 5, 'month': 'may' } }
appointment.update(appointment2)
appointment

輸出:

{
? ? 'gym': {'day': 5, 'month': 'may'},?
? ? 'soccer': {'day': 20, 'month': 'april'}
}

原文鏈接:https://blog.csdn.net/yawei_liu1688/article/details/126563474

欄目分類
最近更新