Python字典的常見操作

1.在leetcode上刷題的時候,經常需要使用統計元素個數,例如
  • words = [“a”,“b”,“c”,“d”,“a”,“c”,“r”]
  • 統計列表words中每個元素及其出現的次數
words = ["a","b","c","d","a","c","r","r"]

#方法1,用Counter
from collections import Counter
words_dict_1 = Counter(words)
##還可以使用dict(Counter(words))將結果轉化爲字典
#將dict按value的值從高到低進行排序
print(words_dict_1.most_common())
# [('a', 2), ('c', 2), ('b', 1), ('d', 1), ('r', 1)]
#只輸出前三個
print(words_dict_1.most_common(3))
# [('r', 2), ('a', 2), ('c', 2)]


#方法2,用字典
words_dict_2 = {}
for word in words:
	#當word不在words_dict_2中的時候,會出現KeyError,所以要單獨判斷
	if word not in words_dict_2:
		words_dict_2[word] = 1
	else:
		words_dict_2[word] += 1
		
#方法3,用默認字典
words_dict_3 = collections.defaultdict(int)
for word in words:
	#words_dict_3是默認字典,且裏面是int,所以當key不在字典中時,返回int的默認值,是0
	words_dict_3[word] += 1

#方法4,用字典+get方法
words_dict_4 = {}
for word in words:
	#get方法,當key不在字典中時,默認返回None,不過這裏將默認值改爲了0,即key不在字典中時,返回0
	words_dict_4[word] = words_dict_4.get(word,0) + 1



print(words_dict_1==words_dict_2==words_dict_3==words_dict_4)
#True
print(words_dict_2)
#{'a': 2, 'c': 2, 'b': 1, 'r': 1, 'd': 1}
  • 1.1 在用1中的方法統計好了每個元素出現的次數的時候,有時需要按某個順序來遍歷dict中的元素。
#如果是用Counter(),那麼有現成的most_common方法可以使用,剩餘的幾種寫法,若想排序,見3.字典的排序
print(words_dict_1.most_common())
  • 1.2 關於添加元素到dict中,若元素不在字典中的情況,以leetcode-49爲例

class Solution(object):
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        # 方法1,用defaultdict並且裏面是list類型
        # ans = collections.defaultdict(list)
        # for s in strs:
        #     #如果當前遍歷到的s不在ans中,那麼其對應的默認值爲[],所以可以直接append
        #     ans[tuple(sorted(s))].append(s)
        # return ans.values()
        
        #方法2,還是使用一般的dict
        ans = {}
        for s in strs:
            #如果當前遍歷到的s不在ans中,那麼其對應的默認值爲[],注意:下面的寫法中正確的
            #是第二種,第一種是不對的
            #ans[tuple(sorted(s))] = ans.get(tuple(sorted(s)),[]).append(s)
            ans[tuple(sorted(s))] = ans.get(tuple(sorted(s)),[])+[s]
        return ans.values()


2.字典的查找
min(record, key=record.get), 返回最小的value對應的key,如果有多個value相同,只返回第一個。
max(record, key=record.get),返回最大的value對應的key,如果有多個value相同,只返回第一個。
3.字典的排序
  • sort()方法只能用於list的排序,具體用法爲:
alist = [1,2,3,4,2,1,5,6,7]
#原地排序,不返回值
alist.sort()
#[1, 1, 2, 2, 3, 4, 5, 6, 7]
print(alist)
  • 要想對字典,字符串,set等進行排序,可以使用sorted()函數,sorted 可以對所有可迭代的對象進行排序操作。返回一個新的list(注意,不管操作什麼對象,都返回list)
>>>alist = [1,5,4,3,2]
>>>sorted(alist)
[1, 2, 3, 4, 5]
>>>strs = "15423aweffASW"
>>>sorted(strs) #字符按ASCII碼排序
['1', '2', '3', '4', '5', 'A', 'S', 'W', 'a', 'e', 'f', 'f', 'w']
>>>record = {1:4,6:3,2:8,9:1,4:10}
>>>sorted(record) #默認按key進行排序(默認只返回包含key的list)
[1, 2, 4, 6, 9]
>>>sorted(record.items()) #默認按key進行排序(返回包含每一個item的list)
[(1, 4), (2, 8), (4, 10), (6, 3), (9, 1)]
Python2:sorted(iterable, cmp=None, key=None, reverse=False)
Python3:sorted(iterable, key=None, reverse=False)
  • 注:cmp可以傳入兩個參數進行比較,key只能傳入一個參數進行比較
>>>record = {1:4,6:3,2:8,9:1,4:10,5:4,8:1,10:1}
>>>sorted(record.items(),key=lambda x:x[1]) #按value從小到大進行排序
[(8, 1), (9, 1), (10, 1), (6, 3), (1, 4), (5, 4), (2, 8), (4, 10)]
#上面的用key等價於下面這一句,不過下面這一句只能在Python2中用
>>>sorted(record.items(),cmp=lambda x,y:cmp(x[1],y[1])) #按value從小到大進行排序
>[(8, 1), (9, 1), (10, 1), (6, 3), (1, 4), (5, 4), (2, 8), (4, 10)]
#在python3中,要想使用cmp,可以用functools.cmp_to_key
>>>import functools
>>> sorted(record.items(),key=functools.cmp_to_key(lambda x,y:x[1]-y[1])) #按value從小到大進行排序
[(8, 1), (9, 1), (10, 1), (6, 3), (1, 4), (5, 4), (2, 8), (4, 10)]




>>>sorted(record.items(),key=lambda x:x[0]) #按key從小到大進行排序
[(1, 4), (2, 8), (4, 10), (5, 4), (6, 3), (8, 1), (9, 1), (10, 1)]

>>>sorted(record.items(),key=lambda x:(x[0],-x[1])) #按key從小到大,value從大到小
#(只有在key相等的時候,纔看value的順序,不過key是不同的,所以沒有意義)進行排序
[(1, 4), (2, 8), (4, 10), (5, 4), (6, 3), (8, 1), (9, 1), (10, 1)]

>>> sorted(record.items(),key=lambda x:(-x[0],x[1])) #按key從大到小,value從大到小
[(10, 1), (9, 1), (8, 1), (6, 3), (5, 4), (4, 10), (2, 8), (1, 4)]

>>> sorted(record.items(),key=lambda x:(x[1],x[0])) #value從小到大,key從小到大
[(8, 1), (9, 1), (10, 1), (6, 3), (1, 4), (5, 4), (2, 8), (4, 10)]

>>> sorted(record.items(),key=lambda x:(x[1],-x[0])) #value從小到大,key從大到小
[(10, 1), (9, 1), (8, 1), (6, 3), (5, 4), (1, 4), (2, 8), (4, 10)]

>>>sorted(record.items(),key=lambda x:(x[0]+x[1],-x[0])) #先按key+value從小到大排序,再按key從大到小排序
[(1, 4), (8, 1), (6, 3), (5, 4), (9, 1), (2, 8), (10, 1), (4, 10)]



#用sorted排序解決leetcode-179
# python2
class Solution(object):
    def largestNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: str
        """
        if not nums:
            return ""
        numbers = [str(number) for number in nums]
        # python2,不支持python3,因爲python3中沒有cmp參數了
        numbers.sort(cmp=lambda x, y: cmp(y + x, x + y))
        return "".join(numbers).lstrip('0') or '0'


# python3
class Solution:
    def largestNumber(self, nums: List[int]) -> str:
        import functools
        if not nums:
            return ""
        numbers = [str(number) for number in nums]
        # python3中可以使用functools.cmp_to_key
        # python中不支持兩個str直接做減法,所以先要轉換成int類型
        numbers.sort(key=functools.cmp_to_key(lambda x, y: int(y + x) - int(x + y)))
        return "".join(numbers).lstrip('0') or '0'

## 現在有一道題,給定一個list,其中可能含有重複元素,現在要求重複元素只保留一個,
## 返回新的list,並且保持原來的順序。

## 例如:
a = [5,5,4,4,6,7,5,8,9,9,2,3,1]
返回的結果是:[5, 4, 6, 7, 8, 9, 2, 3, 1]

使用下面語句即可:
#先將a轉換爲set,再轉回list,這樣可以去重,然後排序,並且排序的規則是按照a原來的順序進行排序(使用a.index)。
sorted(list(set(a)),key=a.index)
參考:爲什麼Python 3.6以後字典有序並且效率更高?
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章