我有一系列名为"x.tif"的文件,其中"x"是整数 我需要将这些文件分类到每个数字范围的文件夹中.

文件夹的顶层应该以百万计,例如,0—999999、1000000—199999 下一级文件夹应以千为单位,例如0—999、1000—1999

与其说是Python让我绊倒了,不如说是计算范围的实际数学,

The end result should look something like this Desired result example

当然,我可以使用硬编码的范围来实现这一点,但我宁愿避免为每百万中的每千个输入一个巨大的elif语句.

我一直在try 使用divmod(),它可以像预期的那样工作,但我不能计算出我需要做什么来使这个动态,以便它可以想象出输入它的任何数字的范围.

def get_number_range(file_to_move): 

    file_number = file_to_move
    try:
        mod_calc_thou = divmod(int(file_number), 1000)
    except ValueError:
        self.mission_failed(file_to_move, reason="Not a number")
        return False, False
    try: 
        mod_calc_mil = divmod(int(file_number), 1000000)
    except ValueError:
        return False, False
    thousands_range = mod_calc_thou[0] + 999
    millions_range = mod_calc_mil[0] + 9999999
    thousands_range_folder = f"{str(mod_calc_thou[0])}-{thousands_range}"
    millionsths_range_folder = f"{str(mod_calc_mil[0])}-{millions_range}"
    print(thousands_range_folder)
    print(millionsths_range_folder)

print("First")
get_number_range("530")
#Should output 0-999 and 0-999999
print("Second")
get_number_range("1842888")
#Should output, 1842000-1842999, 1000000-1999999
print("Third")
get_number_range("19874")
#Should output 19000-19999, 0-999999

推荐答案

您可以使用modulo %运算来计算文件号的提醒,并减go 该提醒以获得范围的基数fi.最高的范围是fi + Li—1.

n = 19874

L1 = 1000000  # Top-level
L2 = 1000  # Next-level

# Compute the base of the ranges
f1 = n - (n % L1)
f2 = n - (n % L2)

# Compute the whole range
r1 = f1, f1 + L1 - 1
r2 = f2, f2 + L2 - 1

print(r2, r1)

这可以很容易地适用于两个以上的级别.

n = 1842888

# The levels in increasing order
levels = [1000, 1000000]

# Compute the base of the ranges
f = [n - (n % l) for l in levels]
# Compute the whole range
r = [(f, f + l - 1) for (f, l) in zip(f, levels)]

print(r)

Python相关问答推荐

如何在Deliveryter笔记本中从同步上下文正确地安排和等待Delivercio代码中的结果?

如何使用Jinja语法在HTML中重定向期间传递变量?

Python在tuple上操作不会通过整个单词匹配

SQLGory-file包FilField不允许提供自定义文件名,自动将文件保存为未命名

将jit与numpy linSpace函数一起使用时出错

'discord.ext. commanders.cog没有属性监听器'

非常奇怪:tzLocal.get_Localzone()基于python3别名的不同输出?

聚合具有重复元素的Python字典列表,并添加具有重复元素数量的新键

将pandas Dataframe转换为3D numpy矩阵

django禁止直接分配到多对多集合的前端.使用user.set()

使用Python更新字典中的值

基于形状而非距离的两个numpy数组相似性

Python Pandas—时间序列—时间戳缺失时间精确在00:00

Pandas—堆栈多索引头,但不包括第一列

如何过滤组s最大和最小行使用`transform`'

Pandas 数据帧中的枚举,不能在枚举列上执行GROUP BY吗?

操作布尔值的Series时出现索引问题

函数()参数';代码';必须是代码而不是字符串

Groupby并在组内比较单独行上的两个时间戳

大Pandas 中的群体交叉融合