python - 通过关联值的函数过滤字典键

标签 python list dictionary count nested

我有一本这样的字典

my_d = {"a": [1, 2, 2, 5, 2],"b": [2, 1, 2, 4, 5],"c": [7, 2, 2, 6, 2],"d": [7, 2, 2, 2, 1]}

我正在寻找字典值包含“2 且小于 2”两次以上的键。在示例中,这将是“a”、“b”、“c”、“d”。以下代码仅查找字典值包含 2 两次以上的那些:

for key, item in my_d.items():
    if item.count(2) > 2:
        print key,

最佳答案

您可以对项目进行排序并检查前两个元素是否≤2:

>>> for key, item in my_d.items():
...   i=sorted(item)
...   if all(map(lambda x:x<=2,i[:2])):
...     print key,
...
a c b d

或者,因为您只有 2 个元素要检查:

>>> for key, item in my_d.items():
...   i=sorted(item)
...   if i[0]<=i[1]<=2:
...     print key,
...
a c b d

关于python - 通过关联值的函数过滤字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27569494/

相关文章:

c - 在C中查找重复项

ios - OpenGL ES 2.0 立方体贴图不显示纹理

c# - C#'s equivalent to Python' s os.path.splitext()?

python - Python 3.3 中的 time.sleep() 函数?

Java For语句和扫描仪输入

vb.net - 带有两个键的字典条目 - VB.net

android - 想要与谷歌地图应用程序相同的卫星 View

Python itertools.compress 的工作方式与 bool 掩码不同。为什么?

android - 如何使用python捕获android屏幕

list - TCL中这两种声明列表的方式有什么区别?