简体   繁体   English

python for循环中的赋值可能吗?

[英]Assignment in python for loop possible?

I have a dictionary d (and a seperate sorted list of keys, keys ). 我有一个字典d (和一个单独的键, keys排序列表)。 I wanted the loop to only process entries where the value is False - so i tried the following: 我希望循环只处理值为False条目 - 所以我尝试了以下内容:

for key in keys and not d[key]:
 #do foo

I suppose my understanding of python sytax is not what i thought it was - because the assignment doesnt suppose to have happened above, and ai get an instanciation error. 我想我对python sytax的理解不是我认为的那样 - 因为赋值不会假设发生在上面,并且ai得到了一个instanciation错误。

The below works of course, but I'd really like to be able to use something like the code above.. possible? 下面的工作当然,但我真的希望能够使用类似上面的代码..可能吗?

for key in keys:
 if d[key]: continue
  #foo time!

Thanks! 谢谢!

Use a genex for this. 为此使用genex。

for key in (k for k in keys if not d[k]):
   ....

If you dict was opposite (True iff the value should be scanned) you could use: 如果你的dict是相反的(如果值应扫描,则为True)你可以使用:

for key in filter(d.get, keys):
    ...
import itertools as it

for key in it.ifilterfalse(d.get, keys):
   ...

itertools often offers the best ways to pack functionality into iterations (==loops;-). itertools经常提供将功能打包到迭代中的最佳方法(==循环;-)。

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

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