python笔记(3)字典操作

python中字典操作

1.字典中键值搜索

d = {'a':1,'b':4,'c':2}
print('a' in d)#true
print('a' in d.keys())#true

在python 2中还有has_key的用法,但是Python 3中已经没有了。

2.字典中按照value排序

方法1

d = {'a':1,'b':4,'c':2}
f = sorted(d.items(),key = lambda x:x[1],reverse = True)
print(f)  #[('b', 4), ('c', 2), ('a', 1)]

方法2

d = {'a':1,'b':4,'c':2}
import operator
f = sorted(d.items(),key = operator.itemgetter(1))
print(f)  #[('a', 1), ('c', 2), ('b', 4)]

方法3

d = {'a':1,'b':4,'c':2}
f = zip(d.values(),d.keys())
sorted(f)
#结果是 [(1, 'a'), (2, 'c'), (4, 'b')]

注意这里zip的用法

leetcode:

给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
例如,给定数组 [1,1,1,2,2,3] , 和 k = 2,返回 [1,2]。
注意:
你可以假设给定的 k 总是合理的,1 ≤ k ≤ 数组中不相同的元素的个数。
你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。

参考代码https://www.cnblogs.com/grandyang/p/5454125.html

使用hash表。利用字典来操作的解法。

class Solution:
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        hashdict = {}
        for i in range(len(nums)):
            if nums[i] in hashdict.keys():
                hashdict[nums[i]] += 1
            else:
                hashdict[nums[i]] = 1

        f = list(zip(hashdict.values(),hashdict.keys()))
        f = sorted(f, reverse = True)

        res = []
        for i in range(k):
            res.append(f[i][1])
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值