Python 學習筆記(2)字典默認值和集合的操作


一、設置字典默認值

#字典的 get方法可以根據獲取

value = some_dict.get(key, default_value

例子如下:

b_dict={"a":1,"b":3,"c":5}
myv=b_dict.get("a",)
print(myv) #結果是 1

如果key不存在,則返回None

設置默認值,setdefault 函數

關於設定值,常見的情況是在字典的值是屬於其它集合,如列表。例如,你可以通過首字母,將一個列表中的單詞分類:

常規方法

[123]: words = ['apple', 'bat', 'bar', 'atom', 'book']
In [124]: by_letter = {}
In [125]: for word in words:
.....: letter = word[0]
.....: if letter not in by_letter:
.....: by_letter[letter] = [word]
.....: else:
.....: by_letter[letter].append(word)
.....:
In [126]: by_letter
Out[126]: {'a': ['apple', 'atom'], 'b': ['bat', 'bar', 'book']}
 
使用setdefault,for循環部分進行如下修改:
  for word in words:
    letter = word[0]
    by_letter.setdefault(letter, []).append(word)
 
  collections模塊有一個很有用的類,defaultdict,它可以進一步簡化上面。傳遞類型或函數以生成每個位置的默認值:

  from collections import defaultdict
  words=["chris","cba","daniel","daniel.zhao"]
  by_letter = defaultdict(list) #默認字典列表?
  for word in words:
  by_letter[word[0]].append(word)
  print(by_letter.get("a"))

  out:['chris', 'cba']

二、集合

可以理解為,只有key沒有value的字典

a={1,2,3,4,5,6,7,8}

或者set([1,2,2,4,5,6,7,7])

out:{1,2,4,5,6,7}

集合常用方法如下:

所有邏輯集合操作都有另外的原地實現方法,可以直接用結果替代集合的內容。對於大的集合,這么做效率更高:

In [141]: c = a.copy()
In [142]: c |= b
In [143]: c
Out[143]: {1, 2, 3, 4, 5, 6, 7, 8}
In [144]: d = a.copy()
In [145]: d &= b
In [146]: d
Out[146]: {3, 4, 5}
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM