1
注意,itertools.groupby假定输入的可迭代对象要使用分组标准排序;即使不排序,至少也要使用指定的标准分组各个元素。
1 #itertools.groupby函数的用法 2 import itertools 3 4 5 6 k1 = list(itertools.groupby('LLLLAAGGG')) 7 print('k1:', k1) 8 # [('L', <itertools._grouper object at 0x000001E0AFBE5880>), ('A', <itertools._grouper object at 0x000001E0AFBE52B0>), ('G', <itertools._grouper object at 0x000001E0AFBE5160>)] 9 print('\n 下面这种为什么返回空:') 10 for i, j in k1: 11 print(i, '->', list(j)) #这种返回的j是空列表,不知道是为什么 12 13 print('\n 为什么这种返回的就有内容:') 14 for char, group in itertools.groupby('LLLLAAAGG'): 15 print(char, '->', list(group)) 16 17 18 print('\n animal未排序时返回的结果格式:') 19 animals = ['duck', 'eagle', 'rat', 'giraffe', 'bear', 'bat', 'dolphin', 'shark', 'lion'] 20 for length, group in itertools.groupby(animals, key = len): 21 print(length, '->', list(group)) 22 23 animals.sort(key = len) 24 print('\n排序后的animal: \n',animals, '\n') 25 26 27 print('\n animal升序后返回的结果格式:') 28 for length, group in itertools.groupby(animals, key = len): 29 print("升序后返回的结果:",length, '->', list(group)) 30 31 32 print('\n animal降序后返回的结果格式:') 33 for length, group in itertools.groupby(reversed(animals), len): 34 print( length, '->', list(group)) 35 36 37 38 39 40 41 42 #itertools.tee 函数产出多个生成器(这个是需要定义返回几个吗),每个生成器都可以产出输入的各个元素 43 print('\n\n 下面测试itertools.tee函数:') 44 r = list(itertools.tee('ABC')) 45 print('返回2个生成器:',r) 46 47 g1, g2 = itertools.tee('ABC') 48 print(next(g1)) 49 print(next(g2)) 50 print(next(g2)) 51 print(list(g1)) 52 print(list(g2)) 53 54 r2 = list(zip(*itertools.tee('ABC'))) 55 print(r2) 56 57 58 59 print('\n返回的结果格式-元组,使用* 元组拆包:', itertools.tee('ABC')) 60 # (<itertools._tee object at 0x000001E0AFB92FC0>, <itertools._tee object at 0x000001E0AE868900>)
1
标签:group,函数,生成器,list,itertools,重新排列,print,groupby From: https://www.cnblogs.com/bravesunforever/p/17417841.html