python 2 strange list comprehension behaviour

后端 未结 2 1679
日久生厌
日久生厌 2021-01-18 08:04

I was looking around list comprehension and saw smth strange. Code:

a = [\'a\', \'a\', \'a\', \'b\', \'d\', \'d\', \'c\', \'c\', \'c\']
print [(len(list(g)),         


        
2条回答
  •  情话喂你
    2021-01-18 08:41

    When you call list() on an itertools._grouper object, you exhaust the object. Since you're doing this twice, the second instance results in a length of 0.

    First:

    if len(list(g))
    

    now it's exhausted. Then:

    (len(list(g)), k))
    

    It will have a length of 0.

    You can nest a generator/comprehension in your list comprehension to exhaust the object and save the relevant data before processing it:

    >>> [(y,x) if y>1 else x for x,y in ((k, len(list(g))) for k, g in groupby(a))]
    [(3, 'a'), 'b', (2, 'd'), (3, 'c')]
    

提交回复
热议问题