listdict = {
'list_1' : ['1'],
'list_2' : ['1','2'],
'list_3' : ['2'],
'list_4' : ['1', '2', '3', '4']
}
print(len(listdict))
例如,這是我的代碼。我希望它列印:
8
如您所見,我已經嘗試了長度,但它當然會列印 4 個串列的數量,但我希望它列印串列中的專案數量。有沒有一種方法可以讓我用一個陳述句來做到這一點,而不是單獨做它們?提前致謝。
我嘗試使用 len(dictionaryname) 但這不起作用
uj5u.com熱心網友回復:
您的字典中有 4 個串列作為值,因此您必須對長度求和:
print(sum(map(len, listdict.values())))
印刷:
8
uj5u.com熱心網友回復:
考慮使用另一個內置函式sum(len是一個內置函式):
>>> listdict = {
... 'list_1' : ['1'],
... 'list_2' : ['1','2'],
... 'list_3' : ['2'],
... 'list_4' : ['1', '2', '3', '4']
... }
>>> sum(len(xs) for xs in listdict.values())
8
順便說一句,由于 python 使用了鴨子型別,使用匈牙利語命名Python 中的變數有點sus ngl ...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/532891.html
標籤:Python列表字典
上一篇:查詢字典串列(python)
下一篇:使用字典中的值過濾資料框
