WordPress网站建设宣传图片

Python获取字典的前x个元素

释放双眼,带上耳机,听听看~!

Python获取字典的前*个元素我们可以使用itertools中的islice函数实现或者是sorted函数、Counter(dict).most_common()函数实现,再Python中列表实现这样的需求就很简单,我们可以直接通过切片获取,不过字典没有切片,我们就先取出所有 keys,再用拿到的key去取value,在组成一个新的字典就可以了。

注意:

sorted函数、Counter(dict).most_common()函数会对字典进行排名,如果你的介意,就请勿使用,不过字典都是用key,这个顺序应该无所谓了。

islice()简介

islice()获取迭代器的切片,消耗迭代器

语法:

islice(iterable, [start, ] stop [, step])

可以返回从迭代器中的start位置到stop位置的元素(返回值是一个迭代器。)。如果stop为None,则一直迭代到最后位置。

示例代码

from itertools import islice

test_list = [1, 2, 3, 4]
islice_re = islice(test_list, 4)
print(type(islice_re))
for i in islice_re:
    print(i)

输出结果

<class 'itertools.islice'>
1
2
3
4

islice()实现取字典的前*个元素

这里以一个有5个元素的字典,我们取前三个为例

from itertools import islice

test_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
islice_re = islice(test_dict, 3)  # islice()获取前3个元素
new_dict = dict()  # 准备一个新字典存放要取的元素
for i in islice_re:
    print(i)
    new_dict[i] = test_dict[i]  # 从旧字典取值赋值到新字典

print(new_dict)
  # 打印新字典查看

输出结果

a
b
c
{'a': 1, 'b': 2, 'c': 3}

sorted() 函数实现

sorted() 函数作用是可以对所有可迭代的对象进行排序操作,返回值是重新排序后的列表。

然后sorted() 函数对于字典{}dict,sorted函数默认只按照dict的key进行排序,所以我们和上面一样,去碧for循环key取value,组成一个新的字典。

更多关于sorted() 函数可以看这里:Python3 sorted() 函数 – 对所有可迭代的对象进行排序操作。

test_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
new_dict = dict()
for key in sorted(test_dict)[:3]:
    new_dict[key] = test_dict[key]
print(new_dict)

输出结果

{'a': 1, 'b': 2, 'c': 3}

Counter(dict).most_common()函数实现

Counter(dict).most_common()函数会将传入的字典返回一个列表,列表中的元素由元组组成(字典的key,value),按照字典value从大到小排序。

返回值是列表,所以我们通过索引索取我们要的数量即可。然后for循环每个元素,组成新的字典。

示例代码

from collections import Counter

test_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

counter_re = Counter(test_dict).most_common()  # 将字典排序 返回列表
counter_re = counter_re[:3]  # 通过索引取前三个
print(counter_re)

new_dict = dict()  # 准备一个新字典存放数据
for i in counter_re:  # 循环列表中的元组 元组第一个是key 第二个是value 存放进新字典new_dict
    # print(i)
    new_dict[i[0]] = i[1]

print(new_dict)

输出结果

[('e', 5), ('d', 4), ('c', 3)]
{'e': 5, 'd': 4, 'c': 3}

给TA打赏
共{{data.count}}人
人已打赏
Python字典Python笔记

Python字典按照值(value)的大小进行排序方法

2023-5-10 19:51:44

Python内置模块Python笔记

Python从路径|URL中获取文件名、文件后缀的方法

2023-5-28 14:35:24

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索
展开目录