Skip to content

Instantly share code, notes, and snippets.

@harunyasar
Created December 12, 2017 11:40
Show Gist options
  • Save harunyasar/e1378eeec2f7ace40c82d03caf8813f7 to your computer and use it in GitHub Desktop.
Save harunyasar/e1378eeec2f7ace40c82d03caf8813f7 to your computer and use it in GitHub Desktop.
itemgetter
from operator import itemgetter
from functools import reduce
leagues = [
{
'country': 'Switzerland',
'teams': ['Young Boys', 'Basel', 'Zürich', 'Grasshoppers', 'St. Gallen', 'Lausanne Sports', 'Thun', 'Luzerns',
'Lugano', 'Sion']
},
{
'country': 'Scotland',
'teams': ['Celtic', 'Rangers', 'Aberdeen', 'Hibernian', 'Motherwell', 'Hearts', 'St. Johnstone', 'Kilmarnock',
'Hamilton', 'Dundee FC', 'Ross County', 'Partick Thistle']
},
{
'country': 'Norway',
'teams': ['Rosenborg', 'Brann', 'Odds BK', 'Haugesund', 'Molde', 'Sarpsborg 08', 'Stromsgodset', 'Viking',
'Aalesund', 'Valerenga', 'Sogndal', 'Lilleström', 'Tromsö', 'Stabaek', 'Bodo / Glimt', 'Start']
}
]
max_team_of_country = max(leagues, key=lambda x: len(x['teams']))
print(f"Country: {max_team_of_country['country']}")
min_team_of_country = min(leagues, key=lambda x: len(x['teams']))
print(f"Country: {min_team_of_country['country']}")
country = itemgetter('country')
order_by_name_of_country = sorted(leagues, key=country)
print(f"Order: {order_by_name_of_country}")
country_order = list(map(country, order_by_name_of_country))
print(f"Order: {country_order}")
lists_of_list_of_teams = list(map(lambda league: league['teams'], leagues))
print(f"Lists of list of teams: {lists_of_list_of_teams}")
list_of_teams = sorted(reduce(lambda x, y: x + y, lists_of_list_of_teams))
print(f"List of teams: {list_of_teams}")
sort_by_number_of_teams = sorted(leagues, key=lambda x: len(x['teams']), reverse=True)
print(f"Sorted by number of teams: {sort_by_number_of_teams}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment