Python max () does not accept keyword arguments

I have a script that I wrote on a machine running Python 2.7.3 that uses the max function with the key along with glob to find the smallest file of a certain type in the directory. I tried transferring this to another machine just to find that it was running Python 2.4.3 and the script was not working.

The problem occurs with the following line:

newest = max(glob.iglob(bDir + '*.[Dd][Mm][Pp]'), key=os.path.getctime)

I looked through the documentation and see that both iglob and max with the key are not available while Python 2.5>

I can change the link to iglob only to glob and get rid of case insensitivity, which works fine. But I'm not sure how to rewrite above without using max along with the key?

+4
source share
3

, Python 2.4, , , , , , . , , , "" , .

# Note: untested
times_files = [(os.path.getctime(f),f) for f in glob.glob(bDir+'*.[Dd][Mm][Pp]')]
newest = max(timed_files)[1] # grab the filename back out of the "max" tuple

(, , , ), @jonrsharpe , sorted key, :

newest = sorted(glob.glob(bDir + '*.[Dd][Mm][Pp]'), key=os.path.getctime)[-1]
+7

Python 2.4.x, sorted key; glob , :

newest = sorted(glob.glob(bDir + '*.[Dd][Mm][Pp]'), key=os.path.getctime)[-1]
+6

, DSU:

try:
    # At least give it a chance, in case a modern version of Python is running,
    # it would be faster
    my_max = max(my_list, key=my_func)
except:
    my_decorated = [(my_func(x), x) for x in my_list]
    my_max = max(my_decorated)[1]

You can even do something higher that overrides the built-in function maxfor your version if you need to do this a lot in code and don't want to put it in every place ..

+1
source

Source: https://habr.com/ru/post/1530038/


All Articles