使用Python min()max()避免数字的字典顺序 [英] Avoid lexicographic ordering of numerical values with Python min() max()

查看:181
本文介绍了使用Python min()max()避免数字的字典顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a script to pull random numbers from a set of values. However, it broke today because min() and max() sort values by lexicographic order (so 200 is considered greater than 10000). How can I avoid lexicographic order here? Len key is on the right track but not quite right. I couldn't find any other key(s) that would help.

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]

返回: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]

返回:lowest_value = 1600 highest_value = 10000

谢谢.

推荐答案

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

You can use key to order by the numeric part of the file:

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

这篇关于使用Python min()max()避免数字的字典顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆