如何使用max()函数获取zip对象中每个键关联的最大值?
Alright, let's break down how to get the result you're after: (1,18) and (4,28) where 18 is the largest snack associated with key 1, and 28 is the largest snack associated with key 4.
First, let's clarify why running max(scoobysnacks) directly won't work:
zip()returns a one-time iterator—once you iterate over it (like withmax()), it's empty.- The default
max()function compares tuples element-wise (first by thescoobyvalue, then thesnackvalue), so it would only return a single tuple ((4,28)in this case), not grouped max values for each key.
Solution 1: Use a Dictionary to Track Grouped Max Values
This is a straightforward, readable approach where we manually track the largest snack for each key:
scooby = [1, 4, 1, 4, 1, 4, 1, 1, 4] snacks = [6, 28, 14, 3, 9, 8, 18, 6, 7] scoobysnacks = zip(scooby, snacks) # Initialize a dictionary to hold the max snack for each key max_snack_by_key = {} for key, snack in scoobysnacks: # Update the max value if the current snack is larger, or the key doesn't exist yet if key not in max_snack_by_key or snack > max_snack_by_key[key]: max_snack_by_key[key] = snack # Convert the dictionary to the tuple format you want result = list(max_snack_by_key.items()) print(result) # Output: [(1, 18), (4, 28)]
Solution 2: Use itertools.groupby (Requires Sorting)
If you prefer using built-in itertools, you can use groupby—but note that groupby only groups consecutive matching keys, so we need to sort the zipped pairs first:
from itertools import groupby scooby = [1, 4, 1, 4, 1, 4, 1, 1, 4] snacks = [6, 28, 14, 3, 9, 8, 18, 6, 7] # First, sort the zipped pairs by the scooby key to group all same keys together sorted_pairs = sorted(zip(scooby, snacks), key=lambda x: x[0]) result = [] # Group by the scooby key, then find the max snack in each group for key, group in groupby(sorted_pairs, key=lambda x: x[0]): # Get the tuple with the largest snack value in the group max_pair = max(group, key=lambda x: x[1]) result.append(max_pair) print(result) # Output: [(1, 18), (4, 28)]
Solution 3: Simplify with collections.defaultdict
This is a slight variation of Solution 1, using defaultdict to avoid checking if a key exists:
from collections import defaultdict scooby = [1, 4, 1, 4, 1, 4, 1, 1, 4] snacks = [6, 28, 14, 3, 9, 8, 18, 6, 7] scoobysnacks = zip(scooby, snacks) # Use defaultdict with a starting value of negative infinity (works for all snack values) max_snack_by_key = defaultdict(lambda: float('-inf')) for key, snack in scoobysnacks: if snack > max_snack_by_key[key]: max_snack_by_key[key] = snack result = list(max_snack_by_key.items()) print(result) # Output: [(1, 18), (4, 28)]
All three methods will give you the desired tuple pair result, grouped by the keys in scooby with their corresponding maximum snack values.
内容的提问来源于stack exchange,提问作者JackedUpDBA

