代码之家  ›  专栏  ›  技术社区  ›  genhernandez

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

  •  1
  • genhernandez  · 技术社区  · 6 年前

    我有一个生成字典列表的函数,如下所示:

    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
         }
    ]
    

    stop_id 在所有的词典中不是1就是2。

    我已经想出了如何使用for循环来实现这一点,但是我似乎无法让下面的一行代码正常工作。我错过什么了吗?

    all((d['stop_id'] == 1 or d['stop_id'] == 2) in d for d in direction_stops)
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   John Kugelman Michael Hodel    6 年前

    摆脱 in d .

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

    您可以使用 in

    all(d['stop_id'] in {1, 2} for d in direction_stops)
    
        2
  •  1
  •   Paweł Drapiewski    6 年前

    正如约翰·库格曼所说,你必须删除 in d 因为 (d['stop_id'] == 1 or d['stop_id'] == 2) 会给你布尔值。以及使用 在d中