简体   繁体   English

如何在for循环和if语句中简化for循环?

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

Can I shorten this code into 1-2 lines?我可以将此代码缩短为 1-2 行吗?

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 循环之一使用字典键它会如何工作。

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).在任何情况下,请不要使用诸如dictlist类的变量名,因为它们已经用于内置类型构造函数,并且将它们重新分配给不同的对象确实很麻烦(在大多数情况下,即使经过仔细考虑和打算,我仍然建议不要这样做)。

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.如果你愿意,你可以把它变成一个像这样的列表理解: [my_dict[a].append(q) for a in my_dict for q in my_list if a in q] ,但是,正如你在评论中看到的,这个不推荐,实际上可能更难阅读和理解。

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.我花了这么长时间才明白, for是按照它们在嵌套循环结构中的顺序编写的,而不是作为要计算的表达式反转。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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