简体   繁体   English

在检查字典列表中的值时将for循环转换为all()

[英]Transforming for-loop into all() when checking values in a list of dictionaries

I have a function that generates a list of dictionaries that looks like this: 我有一个函数生成一个如下所示的字典列表:

direction_stops = [
    {
        'direction_id': 0,
        'stop_id': 1,
        'id': 'df268ccf-1291-4fce-a4c5-d348cbbb95c7',
        'sequence': 1
    },
    {
        'direction_id': 1,
        'stop_id': 1,
        'id': '55e62e15-4b44-4e71-bf5d-27c6d4fb9add',
        'sequence': 1},
    {
        'direction_id': 0,
        'stop_id': 2,
        'id': '7fde3df9-9850-49f1-86bc-511ae2913379',
        'sequence': 2
    },
    {
        'direction_id': 1,
         'stop_id': 2,
         'id': '2ed4053f-b5e0-4df1-b655-d0f23d65a698',
         'sequence': 2
     }
]

And I am trying to assert that the value for stop_id in all the dictionaries is either 1 or 2. 我试图断言所有词典中stop_id的值是1或2。

I have figured out how to do that using a for-loop, but I can't seem to get the following one-liner to work. 我已经弄清楚如何使用for循环来做到这一点,但我似乎无法使下面的单行工作。 Am I missing something? 我错过了什么吗?

all((d['stop_id'] == 1 or d['stop_id'] == 2) in d for d in direction_stops)

Get rid of in d . 摆脱in d

all((d['stop_id'] == 1 or d['stop_id'] == 2) for d in direction_stops)

You can shorten the equality checks using in : 您可以使用in缩短相等性检查:

all(d['stop_id'] in {1, 2} for d in direction_stops)

As John Kugelman sad, you must delete in d because (d['stop_id'] == 1 or d['stop_id'] == 2) will give you boolean value. 正如John Kugelman所伤心的那样,你必须in d删除因为(d['stop_id'] == 1 or d['stop_id'] == 2)会给你布尔值。 And using in d will compare it with each dictonary given by for loop. 并且in d使用将它与for循环给出的每个dictonary进行比较。 And this will give you of course false values in every comparision. 在每次比较中,这都会给你带来虚假的价值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM