![]() |
|
[Tut] How to Find the Max of List of Lists in Python? - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] How to Find the Max of List of Lists in Python? (/thread-95026.html) |
[Tut] How to Find the Max of List of Lists in Python? - xSicKxBot - 05-13-2020 How to Find the Max of List of Lists in Python? Problem: Say you have a list of lists (nested list) and you want to find the maximum of this list. It’s not trivial to compare lists—what’s the maximum among lists after all? To define the maximum among the inner lists, you may want to consider different objectives.
Example: Given list of lists Code: [[1, 1, 1], [0, 2, 0], [3, 3, -1]]
So how do you accomplish this? Solution: Use the Code: max()Syntax: The Code: max()Code: max(iterable, key=None)Arguments: Argument | Description Code: iterableThe values among which you want to find the maximum. In our case, it’s a list of lists. Code: key(Optional. Default Code: NoneLet’s study the solution code for our different versions of calculating the maximum “list” of a list of lists (nested list). Code: lst = [[1, 1, 1], [0, 2, 0], [3, 3, -1]] # Maximum using first element
print(max(lst, key=lambda x: x[0]))
# [3, 3, -1] # Maximum using third element
print(max(lst, key=lambda x: x[2]))
# [1, 1, 1] # Maximum using sum()
print(max(lst, key=sum))
# [3, 3, -1] # Maximum using max
print(max(lst, key=max))
# [3, 3, -1] # Maximum using min
print(max(lst, key=min))
# [1, 1, 1]Try it yourself in our interactive code shell: https://repl.it/@finxter/maxlistoflists?lite=true Related articles:
Where to Go From Here? Enough theory, let’s get some practice! To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs? Practice projects is how you sharpen your saw in coding! Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people? Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner. Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home. Join the free webinar now! |