I have a list of durations like below
['5d', '20h', '1h', '7m', '14d', '1m']
where d
stands for days, h
stands for hours and m
stands for minutes.
I want to get the highest duration from this list(14d
in this case). How can I get that from this list of strings?
max() is an inbuilt function in Python programming language that returns the highest alphabetical character in a string.
sort(key=len) will sort your list of strings by their length. The longest would be a[-1], and the second longest would be a[-2]. `
In a traditional approach we will capture the first element in the list length setting it to a variable named longestString. Next we will iterate over a list checking each element and comparing it to the longestString length. If the length is greater than the previous we will set the longestString element to the current element.
In this, we run a loop to keep a memory of longest string length and return the string which has max length in list. This method can also be used to solve this problem. In this, we use inbuilt max () with “len” as key argument to extract the string with the maximum length. Attention geek!
How can I get max length record from the List? List<string> strings = new List<string> (); strings.Add ("001"); strings.Add ("00121"); strings.Add ("001123123"); strings.Add ("00144"); string longest = strings.OrderByDescending (s => s.Length).First ();
In a comparable example we demonstrate how to find the maximum length string in a collection using groovy. In a traditional approach we will capture the first element in the list length setting it to a variable named longestString. Next we will iterate over a list checking each element and comparing it to the longestString length.
np.argmax
on pd.to_timedelta
:
import numpy as np
import pandas as pd
durations = ['5d', '20h', '1h', '7m', '14d', '1m']
durations[np.argmax(pd.to_timedelta(durations))]
Out[24]: '14d'
pd.to_timedelta
turns a string into a duration (source), and np.argmax
returns the index of the highest element.
Pure python solution. We could store mapping between our time extensions (m
, h
, d
) and minutes (here time_map
), to find highest duration. Here we're using max()
with key
argument to apply our mapping.
inp = ['5d', '20h', '1h', '7m', '14d', '1m']
time_map = {'m': 1, 'h': 60, 'd': 24*60}
print(max(inp, key=lambda x:int(x[:-1])*time_map[x[-1]])) # -> 14d
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With