首页 > 解决方案 > 按累进数字排序

问题描述

我最近开始使用 python,我正在寻找一种逐步订购数字的方法

例如,当我从事会计工作时,基本的资产负债表结构如下:

1 - Asset
1.1 - Asset short term
1.1.1 - xxxxxxxxx
11102312313 - Cash (Accounting account)

并且对于负债 (2) 、费用 (3) 收入 (4) 重复

我怎样才能像上面的例子一样订购,因为如果我直接在 Excel 上订购,它会这样:

1
2
3
4
100000000
1.1
1.1.1
etc..

但我确实需要将列表作为第一个示例

标签: python

解决方案


好的!这对于 Python 初学者来说并非易事,但非常易于管理。不会在这里做你的工作,但会让你走上正确的道路:

  • 假设您有一个字符串列表,["1 - Asset", "1.1 - Asset short term", ...]
  • 您需要对该列表进行排序(教程sorted()),因此您需要在该列表中使用 Python 的内置函数
  • sorted默认会按字母排序,这似乎不是你想要的
  • 要教它其他排序方法,您需要实现 a key,即某个可以正确比较的类(或更一般地,类型)或函数返回值(如<, >, >=)。例如,以类似模式开头的字符串*.*应该总是>比以像 10000000 这样的普通数字开头的字符串。
  • 那么它只是sortedlist = sorted(inputlist, key=accountingkey)

一个典型的键类可能看起来像


def extract_ordinal_from_string(string):
    hyphenposition = string.find(" -")
    if hyphenposition < 0:
         raise Exception(f"Row doesn't contain ' -', can't be sorted: {string}")
    return string[:hyphenposition]


class accounting_key:
    def __init__(self, string):
        self.key = extract_ordinal_from_string(string)
        self.dot = "." in self.key

    def __lt__(other):
        """
        lt: less-than (<) comparison operator
        """

        otherkey = extract_ordinal_from_string(other)
        otherdot = "." in otherkey

        if otherdot and self.dot:
            """"
            Both contain dots.
            Lets put them both in tuples, compare these:
            (1,1,0) < (1,2)
            """
            selftuple = tuple(int(substring) for substring in self.key.split("."))
            othertuple = tuple(int(substring) for substring in otherkey.split("."))
            return selftuple < othertuple

        if not self.dot and not otherdot:
            return int(self.key) < int(otherkey)

        if self.dot and not otherdot:
        ### And so on, up to you to implement
        

推荐阅读