简体   繁体   中英

How can I create a list comprehension out of this deeply-nested 'for' loop?

for role in self.collections[server.id][user.id]:
    for requested_set in self.roles[server.id]['sets']:
        if role in self.roles[server.id]['sets'][requested_set]['roles']:
            if requested_set not in requested_sets:
                requested_sets[requested_set] = []
            requested_sets[requested_set].append(role)

I tried to do this in steps.

Line 1 can be written as [x for x in self.collections[server.id][user.id]] .

Line 2 can be written as [x for x in self.roles[server.id]['sets']] .

Line 3 is where I get confused, as it incorporates line 1.

I started attempting as: [x for x in (x for x in self.collections[server.id][user.id]) if x in self.roles[server.id]['sets'][requested_set]['roles']]

However I see that I will need to incorporate a new variable to represent the absent requested_set variable. Is there a way I can put this all in one line?

Putting all of this code into one line would be very inadvisable. Although I personally like list comprehensions, some people find them complicated. If this code has a possibility of being edited later, it would be better not write this on one line for maintenance purposes. The true cost of code is maintenance. AND, with my current knowledge, it is impossible to get that requested_set variable before its declaration. The code is simply too convoluted for it to be on one line.

However, it is not my place to tell you how to write your code. Because of the requested-set variable, it is impossible to put this all on one line, but it is possible in two lines:

for requested_set in self.roles[server.id]['sets']:
    requested_sets[requested_set] = [role for role in self.collections[server.id][user.id] if role in self.roles[server.id]['sets'][requested_set]['roles']]

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.

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