網站首頁 編程語言 正文
字典求和
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
相關推薦
- 2022-04-10 微信小程序與普通網頁的區別是什么
- 2022-03-21 C++存儲方案和動態分配_C 語言
- 2023-07-10 Gateway服務網關
- 2022-07-31 Android項目開發常用工具類LightTaskUtils源碼介紹_Android
- 2022-02-26 Echarts - 更改圖表圖例(legend)自定義顏色(并與數據段顏色對應)
- 2022-05-09 使用Dockerfile實現數據卷的掛載問題(推薦)_docker
- 2022-08-06 C語言基于EasyX繪制時鐘_C 語言
- 2023-03-29 Python-apply(lambda?x:?)的使用及說明_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支