用理解简化嵌套的for循环

时间:2015-04-03 19:32:27

标签: python dictionary list-comprehension dictionary-comprehension

我正在尝试通过字典简化嵌套for循环来构建唯一值列表(房间大小是嵌套字典值中的列表)。我已经将代码缩减到4行,但是如果它可以通过列表理解以任何方式减少到1行,那就很奇怪。

这是一个示例python词典:

otas = {
    Orbitz: {
        u'Las Vegas': [u'1 Bedroom Suite B-side']
    },
    Expedia: {
        u'Los Angeles': [u'2 Bedroom Lockoff', u'1 Bedroom Deluxe (A-side)', u'3 Bedroom Deluxe']
    },
    Priceline: {
        u'New York': [u'1 Bedroom Deluxe (A-side)']
    },
    Travelocity: {
        u'Chicago': [u'1 Bedroom Deluxe (A-side)', u'2 Bedroom Lockoff']
    }
}

这是四行代码:

rooms = []
for resort in otas.values():
    for room in resort.values():
        rooms += [r for r in room if r not in rooms]

我知道没有什么错误与我目前正在做的方式。如果可以的话,我很好奇。

3 个答案:

答案 0 :(得分:2)

我想你可以使用三重 - "嵌套"理解。

rooms = {roomtype
         for service  in otas
         for location in otas[service]
         for roomtype in otas[service][location]}

如果你想要一个列表,只需将其包含在list的调用中。

答案 1 :(得分:1)

如果您想要的是在otas字典中没有重复的房间,那么:

rooms = set([r for resort in otas.values() for room in resort.values() for r in room])

答案 2 :(得分:1)

你可以试试这个

rooms = list(set(reduce(lambda x, y: x+y, [item for x in otas.values() for item in x.values()])))
相关问题