I have the following code to find the longest list in a list of lists:
max_len = max([len(path) for path in paths])
[path for path in paths if len(path) == max_len][0]
Each path
is a list of integers. paths
doesn't have to be a list. So if I have, for example:
path_a = [1, 2, 3]
path_b = [1, 4]
path_c = [3, 5, 6, 2, 7]
Then the code should give me path_c
. In case of ties, it doesn't matter what's returned as long as it has the correct (longest) length.
Is there a more pythonic way?
-
\$\begingroup\$ How long lists are we dealing with? Are you sure you need a list? What kind of lists? \$\endgroup\$Simon Forsberg– Simon Forsberg2015年05月24日 00:56:14 +00:00Commented May 24, 2015 at 0:56
-
\$\begingroup\$ @SimonAndréForsberg see edit, I hope it's clearer now. \$\endgroup\$jcm– jcm2015年05月24日 01:14:14 +00:00Commented May 24, 2015 at 1:14
1 Answer 1
Note that your code iterates over paths
twice: once to calculate the max length,
and one more time to find all elements that have the max length.
It would be better to iterate only once, keeping track of the max value, and the item that had the max value. At the end of the iteration (single pass), return the item that had the max value.
You can code this algorithm yourself,
and in many programming languages you would have to.
In Python,
the max
built-in takes a key
parameter,
to perform such "max by" operation.
The key
parameter must be a one-argument function.
For each item in the collection,
the function will receive the item,
and should return a value that will be used as the rank of the item.
In your example, the rank of each item is its length. That gives this simple pythonic code:
max(paths, key=lambda coll: len(coll))
... which gets even simpler with η-reduction to just (thanks @Gareth!):
max(paths, key=len)
-
\$\begingroup\$ with more than 1 argument does the
key=len
need to be in brackets?max(a,b,c, [key=len])
? \$\endgroup\$mLstudent33– mLstudent332019年09月12日 10:08:01 +00:00Commented Sep 12, 2019 at 10:08