简体   繁体   中英

How to simplify a for loop in a for loop and an if statement?

Can I shorten this code into 1-2 lines?

I've tried making it into a list comprehension but I'm not sure how it would work if one of the for loops uses a dictionary key.

for a in dict.keys():  
    for q in list:  
        if a in q:  
            dict[a].append(q)  

This code works well to find if the items in the list are one of the dictionary's keys and stores the item as a value under that dictionary key if it is, but I'm hoping to figure out if I can simplify it more.

Initially I wanted to suggest this:

{k: v for v in mylist for k in mydict if k in v}

But then I've noticed you're actually modifying your inputs along the way and it's not what is going on. This should actually do the same (I've taken an assumption or two about the inputs):

for key in mydict.keys():
    mydict[key].extend((i for i in mylist if key in i))

But a piece of unsolicited advice. The code snippet really does not need shortening. Rather it could do with a bit more verbosity and more descriptive variable names to guide a reader through and helping to understand what is going on.

In any case, please, do not use variable names like dict or list as those are already used for built-in type constructor and it really is asking for trouble to reassign them to a different object (under most circumstances and even if carefully considered and intended, I'd still advise against it).

If you want, you can turn it into a list comprehension like so: [my_dict[a].append(q) for a in my_dict for q in my_list if a in q] , but, as you can see in the comments, this is not recommended and may actually be harder to read & understand.

What the loops use to iterate over is not important. What I took so time time to understand is that the for get written in the order they are in the nested loop structure, not inverted as the expression to evaluate.

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