避免使用 Python min() max() 对数值进行字典顺序排序

Avoid lexicographic ordering of numerical values with Python min() max()

我有一个脚本可以从一组值中提取随机数。但是,它今天坏了,因为 min()max() 按字典顺序对值进行排序(因此 200 被认为大于 10000)。我怎样才能在这里避免字典顺序? Len 关键在正确的轨道上,但不太正确。我找不到任何其他有帮助的密钥。

data_set = 1600.csv, 2405.csv, 6800.csv, 10000.csv, 21005.csv

第一次尝试:

highest_value = os.path.splitext(max(data_set))[0]
lowest_value = os.path.splitext(min(data_set))[0]

returns: lowest_value = 10000 highest_value = 6800

第二次尝试:

highest_value = os.path.splitext(max(data_set,key=len))[0]
lowest_value = os.path.splitext(min(data_set,key=len))[0]

returns: lowest_value = 1600 highest_value = 10000

谢谢。

您可以使用key按文件的数字部分排序:

data_set = ['1600.csv', '2405.csv', '6800.csv', '10000.csv', '21005.csv']

highest = max(data_set, key=lambda x: int(x.split('.')[0]))
lowest = min(data_set, key=lambda x: int(x.split('.')[0]))

print(highest) # >> 21005.csv
print(lowest)  # >> 1600.csv

你很接近。不要将 splittext 的结果与 len 函数一起使用,而是使用 int 函数:

>>> from os.path import splitext
>>> data_set = ['1600.csv', '2405.csv', '6800.csv', '10000.csv', '21005.csv']
>>> def convert_to_int(file_name):
        return int(splitext(file_name)[0])

>>> min(data_set, key=convert_to_int)
'1600.csv'
>>> max(data_set, key=convert_to_int)
'21005.csv'

当然,此解决方案假定您的文件名将仅由数值组成。