I'm trying to simplify a nested for loop through a dictionary to build a list of unique values (the room sizes that are lists in the nested dictionary values). I have gotten the code reduced down to 4 lines, but was curious if it can be reduced to 1 line through list comprehension in any way.
This is an example python dictionary:
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']
}
}
And this is the four lines of code:
rooms = []
for resort in otas.values():
for room in resort.values():
rooms += [r for r in room if r not in rooms]
I know there is nothing wrong with the way i'm currently doing it. I'm mostly curious if it can be done.
I guess you could use a triply-"nested" set comprehension.
rooms = {roomtype
for service in otas
for location in otas[service]
for roomtype in otas[service][location]}
If you want a list back, just wrap that in a call to list
.
如果您要的是在otas词典中没有重复的房间,则:
rooms = set([r for resort in otas.values() for room in resort.values() for r in room])
你可以试试这个
rooms = list(set(reduce(lambda x, y: x+y, [item for x in otas.values() for item in x.values()])))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.