gpt4 book ai didi

python - 在 defaultdict(list) python 中查找元素的数量

转载 作者:行者123 更新时间:2023-11-28 21:27:43 26 4
gpt4 key购买 nike

一个简单的问题?我想知道是否有一种 pythonic 方式来获取以下内容。

我有一个默认字典(列表)

 foo = {"a":[1,2,3], "b":[3]....} and so on.

是否有一种 pythonic 方式来编写一个函数,它只返回列表长度超过“n”的键

例如

 def return_keys_based_on_value_length(num,dictionary):
key_list = []
for k,v in dictionary:
if len(v)>= num:
key_list.append(k)
return key_list

有没有pythonic的方法来做到这一点?谢谢

最佳答案

foo = {"a":[1,2,3], "b":[3], "c":[1,2], "d":[1,2,3,4]}

n = 2

my_list = [key for key,val in foo.iteritems() if len(val) > n]

结果:

>>> my_list
['a', 'd']

关于python - 在 defaultdict(list) python 中查找元素的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10166159/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com