Skip to content

Instantly share code, notes, and snippets.

@stilllisisi
Last active February 18, 2020 03:04
Show Gist options
  • Save stilllisisi/32e36e45b26e521f25b310b231d32076 to your computer and use it in GitHub Desktop.
Save stilllisisi/32e36e45b26e521f25b310b231d32076 to your computer and use it in GitHub Desktop.
【python-列表/字典处理】使用groupby将列表元素分类
from itertools import groupby
def height_class(h):
if h> 180:
return "tall"
elif h<160:
return "short"
else:
return "middle"
friends = [191,144,142,170,177,188,293]
friends = sorted(friends, key = height_class)
for m, n in itertools.groupby(friends, key=height_class):
print(m)
print(list(n))
#middle
#[170, 177]
#short
#[144, 142]
#tall
#[191, 188, 293]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment