简体   繁体   English

如何在while循环中使用列表理解

[英]how to make list comprehension using while in loop

I have such loop: 我有这样的循环:

ex = [{u'white': []},
 {u'yellow': [u'9241.jpg', []]},
  {u'red': [u'241.jpg', []]},
   {u'blue': [u'59241.jpg', []]}]


for i in ex:
    while not len(i.values()[0]):
        break
    else:
        print i
        break

I need always to return first dict with lenght of values what is higher then 0 but i want to make it with list comprehension 我总是需要返回第一个具有长度值的字典,然后是大于0的值,但是我想通过列表理解来使它返回

A list comprehension would produce a whole list, while you want just one item . 列表理解将产生整个列表,而您只需要一个项目

Use a generator expression instead, and have the next() function iterate to the first value: 改用生成器表达式,并使next()函数迭代到第一个值:

next((i for i in ex if i.values()[0]), None)

I've given next() a default to return as well; 我给了next()一个默认的返回值。 if there is no matching dictionary, None is returned instead. 如果没有匹配的字典,则返回None

Demo: 演示:

>>> ex = [{u'white': []},
...  {u'yellow': [u'9241.jpg', []]},
...   {u'red': [u'241.jpg', []]},
...    {u'blue': [u'59241.jpg', []]}]
>>> next((i for i in ex if i.values()[0]), None)
{u'yellow': [u'9241.jpg', []]}

You should, however, rethink your data structure. 但是,您应该重新考虑数据结构。 Dictionaries with just one key-value pair suggest to me you wanted a different type instead; 只有一对键值对的字典向我建议您改用另一种类型。 tuples perhaps: 元组也许:

ex = [
    (u'white', []),
    (u'yellow', [u'9241.jpg', []]),
    (u'red', [u'241.jpg', []]),
    (u'blue', [u'59241.jpg', []]),
]

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

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