Use of yield with a dict comprehension

前端 未结 4 930
醉梦人生
醉梦人生 2021-02-07 01:53

As a contrived example:

myset = set([\'a\', \'b\', \'c\', \'d\'])
mydict = {item: (yield \'\'.join([item, \'s\'])) for item in myset}

and

4条回答
  •  南旧
    南旧 (楼主)
    2021-02-07 02:35

    I find! ^_^

    In normal life, expression

    print {item: (yield ''.join([item, 's'])) for item in myset} 
    

    evaluate like this:

    def d(myset):
        result = {}
        for item in myset:
            result[item] = (''.join([item, 's']))
        yield result
    
    print d(myset).next()
    

    Why yield result instead return result? I think it is necessary to support nested list comprehensions* like this:

    print {i: f.lower() for i in nums for f in fruit}  # yes, it's works
    

    So, would look like this code?

    def d(myset):
        result = {}
        for item in myset:
            result[item] = (yield ''.join([item, 's']))
        yield result
    

    and

    >>> print list(d(myset))
    ['as', 'cs', 'bs', 'ds', {'a': None, 'b': None, 'c': None, 'd': None}]
    

    First will be returned all values of ''.join([item, 's']) and the last will be returned dict result. Value of yield expression is None, so values in the result is None too.

    * More correct interpretation of evaluate nested list comprehensions:

    print {i: f.lower() for i in nums for f in fruit}
    
    # eval like this:
    
    result = {}
    for i, f in product(nums, fruit): # product from itertools
        key, value = (i, f.lower())
        result[key] = value
    print result
    

提交回复
热议问题