Generator Comprehension different output from list comprehension?

后端 未结 4 1295
一向
一向 2020-12-05 09:55

I get different output when using a list comprehension versus a generator comprehension. Is this expected behavior or a bug?

Consider the following setup:

         


        
4条回答
  •  孤街浪徒
    2020-12-05 10:55

    Both are generator object. The first one is just a generator and the second a generator in a generator

    print list( [c[k] for k in unique_keys] for c in all_configs)
    [[1, 3], [2, 2]]
    print list( (c[k] for k in unique_keys) for c in all_configs)
    [ at 0x000000000364A750>,  at 0x000000000364A798>]
    

    When you use zip(* in the first expression nothing happens because it is one generator that will return the list same as list() would do. So it returns the output you would expect. The second time it zips the generators creating a list with the first generator and a list with the second generator. Those generators on there own have a differnt result then the generator of the first expression.

    This would be the list compression:

       print [c[k] for k in unique_keys for c in all_configs]
       [1, 2, 3, 2]
    

提交回复
热议问题