简体   繁体   English

Python max()不带关键字参数

[英]Python max() takes no keyword arguments

I have a script that I wrote on a machine running Python 2.7.3 that utilizes the max function with a key along with glob to find the youngest file of a specific type in a directory. 我有一个脚本,我在运行Python 2.7.3的机器上编写,它利用带有键的max函数和glob来查找目录中特定类型的最年轻文件。 I tried to move this onto another machine only to discover that it's running Python 2.4.3 and the script doesn't work as a result. 我试图将它移动到另一台机器上,但发现它正在运行Python 2.4.3并且脚本不能正常工作。

The problem arises with the following line: 问题出现在以下行:

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

I've looked up the documentation and can see that both iglob and max with a key aren't available until Python 2.5 > 我查了一下文档,可以看到iglob和max都带有密钥,直到Python 2.5>

I can change the iglob reference to just glob and get rid of the case insensitivity which works fine. 我可以将iglob引用更改为只是glob并摆脱不区分大小写的工作正常。 But I'm not sure how to rewrite the above without using max along with a key? 但我不知道如何在不使用max和键的情况下重写上述内容?

I'm not certain what tools Python 2.4 has access to, but I'm pretty sure you still have list comprehensions, so you could tuple your list together with the key you want to use, compare, and then unpack. 我不确定Python 2.4可以访问哪些工具,但我很确定你仍然有列表推导,所以你可以将你的列表与你想要使用的密钥一起编组,比较,然后解压缩。 This works because tuples compare element-wise, so if you put the "key" at the front of your tuples, it'll act as the primary comparator. 这是因为元组在元素方面比较,所以如果你把“密钥”放在元组的前面,它将作为主要的比较器。

# 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

Alternately (and likely faster, if it matters for your use case), as @jonrsharpe pointed out , the sorted function does allow a key argument, so you could also sort your list and grab the last item: 或者(并且可能更快,如果它对你的用例很重要),正如@jonrsharpe所指出的sorted函数确实允许一个key参数,所以你也可以对列表进行排序并获取最后一项:

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

In Python 2.4.x, sorted does take a key ; 在Python 2.4.x中, sorted 确实需要一个key ; you can apply this to your glob and take the last item, for example: 你可以将它应用于你的glob并取最后一项,例如:

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

Just write your own, using the classic DSU method: 只需使用经典的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 could even do something that the top, that overrides the built-in max function for your version, if you need to do this a lot in the code and don't want to put this in every location... 你甚至可以做一些顶级的东西,它会覆盖你的版本的内置max函数,如果你需要在代码中做很多事情并且不想把它放在每个位置......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM