Skip to content

Instantly share code, notes, and snippets.

@msyvr
Last active September 30, 2021 03:45
Show Gist options
  • Save msyvr/68e9f86016194584005f0e92369251b4 to your computer and use it in GitHub Desktop.
Save msyvr/68e9f86016194584005f0e92369251b4 to your computer and use it in GitHub Desktop.
use python lambda to set key for max function applied to lists and nested lists
a = (0, 1, 0)
b = (1, -1, 1)
c = [a, b, b]
d = [b, a, a]
e = [c, d]
# user selects tuple index for comparison
index_okay = False
while not index_okay:
try:
print(f'Index must be an int: 0 <= index < {len(a)}.')
which_index = int(input('Tuple index to compare: '))
if type(which_index) == int and which_index in range(len(a)):
index_okay = True
except:
pass
# using 1. a function then 2. a lambda, set the 'key' argument for 'max' to the 'which_index' element of the item being evaluated in the list-of-tuples (or the list-of-lists for the nested list-of-list-of-tuples, noting that the key arg for the (inner) list-of-tuples will default to index 0)
# set the key using a function
def key_func(x):
return x[which_index]
print(f'\nc is: {c}\n')
print(f'max for index {which_index} using a function to set the comparator key is:\n{max(c, key = key_func)}')
# set the key using a lambda in the max function
print(f'max for index {which_index} using lambda to set the comparator key is:\n{max(c, key = lambda x: x[which_index])}')
# e is a list of list-of-tuples, and the index applies to the (outer) list while the index for the list-of-tuples will default to 0: explicitly, c and d will use which_index, while the index for a and b defaults to 0
print(f'\ne is: {e}\n')
print(f'max for index {which_index} (lambda to get key) is:\n{max(e, key = lambda x: x[which_index])}')
# works for min
print(f'min for index {which_index} (lambda to get key) is:\n{min(e, key = lambda x: x[which_index])}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment