代码之家  ›  专栏  ›  技术社区  ›  Mez

日期顺序输出?

  •  20
  • Mez  · 技术社区  · 17 年前

    我想知道是否有一种快速而简单的方法来输出用python给出的数字的序号。

    例如,给定数字 1 ,我想输出 "1st" 2 , "2nd" ,等等,等等。

    这是为了和面包屑路径中的日期一起工作

    Home >  Venues >  Bar Academy >  2009 >  April >  01 
    

    是当前显示的内容

    我想买些符合

    Home >  Venues >  Bar Academy >  2009 >  April >  1st
    
    14 回复  |  直到 8 年前
        1
  •  33
  •   Mez    13 年前

    或者缩短大卫的回答:

    if 4 <= day <= 20 or 24 <= day <= 30:
        suffix = "th"
    else:
        suffix = ["st", "nd", "rd"][day % 10 - 1]
    
        2
  •  29
  •   CTT    17 年前

    下面是一个更通用的解决方案:

    def ordinal(n):
        if 10 <= n % 100 < 20:
            return str(n) + 'th'
        else:
           return  str(n) + {1 : 'st', 2 : 'nd', 3 : 'rd'}.get(n % 10, "th")
    
        3
  •  12
  •   alukach    12 年前

    不确定5年前你问这个问题时它是否存在,但是 inflect 包具有执行所需操作的功能:

    >>> import inflect
    >>> p = inflect.engine()
    >>> for i in range(1,32):
    ...     print p.ordinal(i)
    ...
    1st
    2nd
    3rd
    4th
    5th
    6th
    7th
    8th
    9th
    10th
    11th
    12th
    13th
    14th
    15th
    16th
    17th
    18th
    19th
    20th
    21st
    22nd
    23rd
    24th
    25th
    26th
    27th
    28th
    29th
    30th
    31st
    
        4
  •  2
  •   eric.frederich    16 年前

    这里它使用字典作为函数或lambda…

    如果你向后看字典,你可以把它读成…

    一切都以“th”结尾

    …除非以1、2或3结尾,否则以“st”、“nd”或“rd”结尾

    …除非以11、12或13结尾,否则以“th”、“th”或“th”结尾

    # as a function
    def ordinal(num):
        return '%d%s' % (num, { 11: 'th', 12: 'th', 13: 'th' }.get(num % 100, { 1: 'st',2: 'nd',3: 'rd',}.get(num % 10, 'th')))
    
    # as a lambda
    ordinal = lambda num : '%d%s' % (num, { 11: 'th', 12: 'th', 13: 'th' }.get(num % 100, { 1: 'st',2: 'nd',3: 'rd',}.get(num % 10, 'th')))
    
        5
  •  2
  •   Vinicius Spader    13 年前

    一个更通用和更短的解决方案(作为函数):

    def get_ordinal(num)
        ldig = num % 10
        l2dig = (num // 10) % 10
    
        if (l2dig == 1) or (ldig > 3):
            return '%d%s' % (num, 'th')
        else:
            return '%d%s' % (num, {1: 'st', 2: 'nd', 3: 'rd'}.get(ldig))
    

    我刚刚把大卫的解决方案和图书馆结合起来(就像Deegeedubs那样)。您甚至可以为真正的数学替换变量(ldig,l2dig)(因为l2dig只使用一次),然后您得到四行代码。

        6
  •  2
  •   Carl    10 年前

    这些天我会用箭 http://arrow.readthedocs.io/en/latest/ (这在09年确实不存在)

    >>> import arrow
    >>> from datetime import datetime
    >>> arrow.get(datetime.utcnow()).format('Do')
    '27th'
    
        7
  •  1
  •   David Z    14 年前

    除了第一,第二和第三,我想他们都加上了…第4、5、6、11、21……噢,哎呀;-)

    我认为这可能有效:

    def ordinal(num):
         ldig = num % 10
         l2dig = (num // 10) % 10
         if l2dig == 1:
             suffix = 'th'
         elif ldig == 1:
             suffix = 'st'
         elif ldig == 2:
             suffix = 'nd'
         elif ldig == 3:
             suffix = 'rd'
         else: 
             suffix = 'th'
         return '%d%s' % (num, suffix)
    
        8
  •  1
  •   SwiftsNamesake    12 年前
    def ordinal(n):
        return ["th", "st", "nd", "rd"][n%10 if n%10<4 and not (10<n%100<14) else 0]
    
        9
  •  1
  •   Eric    8 年前

    我做了一个在这种情况下似乎有效的函数。只需传入一个日期对象,它将使用day来计算后缀。希望它有帮助

    from datetime import date
    def get_day_ordinal(d):
    
        sDay = '%dth'
        if d.day <= 10 or d.day >= 21:
            sDay = '%dst' if d.day % 10 == 1 else sDay
            sDay = '%dnd' if d.day % 10 == 2 else sDay
            sDay = '%drd' if d.day % 10 == 3 else sDay
    
        return sDay % d.day
    
    d = date.today()
    print get_day_ordinal(d)
    
        10
  •  0
  •   deegeedubb    16 年前

    下面是一个更简短的通用解决方案:

    def foo(n):
        return str(n) + {1: 'st', 2: 'nd', 3: 'rd'}.get(4 if 10 <= n % 100 < 20 else n % 10, "th")
    

    虽然上面的其他解决方案乍一看可能更容易理解,但在使用较少的代码的情况下,这也同样有效。

        11
  •  0
  •   not-just-yeti    14 年前

    修正为负输入,基于Eric.Frederich's Nice Sol'n(刚刚添加 abs 使用时 % ):

    def ordinal(num):
        return '%d%s' % (num, { 11: 'th', 12: 'th', 13: 'th'}.get(abs(num) % 100, { 1: 'st',2: 'nd',3: 'rd',}.get(abs(num) % 10, 'th')))
    
        12
  •  0
  •   Houngan    12 年前

    我想在我的一个项目中使用序数,在几个原型之后,我认为这个方法虽然不小,但对于任何正整数都有效,是的,任何整数。

    它的工作原理是确定数字在20以上或以下,如果数字在20以下,它将把int 1转换成字符串1st、2、2nd、3、3rd,其余的都将添加“st”。

    对于超过20的数字,将需要最后一个和第二个到最后一个数字,我分别调用了十位数和单位,然后测试它们,看看在数字上加什么。

    顺便说一句,这是在python中,所以我不确定其他语言是否能够找到字符串上的最后一个或第二个到最后一个数字,如果他们这样做的话,应该很容易翻译。

    def o(numb):
        if numb < 20: #determining suffix for < 20
            if numb == 1: 
                suffix = 'st'
            elif numb == 2:
                suffix = 'nd'
            elif numb == 3:
                suffix = 'rd'
            else:
                suffix = 'th'  
        else:   #determining suffix for > 20
            tens = str(numb)
            tens = tens[-2]
            unit = str(numb)
            unit = unit[-1]
            if tens == "1":
               suffix = "th"
            else:
                if unit == "1": 
                    suffix = 'st'
                elif unit == "2":
                    suffix = 'nd'
                elif unit == "3":
                    suffix = 'rd'
                else:
                    suffix = 'th'
        return str(numb)+ suffix
    

    为了便于使用,我调用了函数“o”,可以通过导入文件名来调用,我先导入序数,然后导入序数.o(数字),将其称为“序数”。

    告诉我你的想法:d

    另外,我把这个答案贴在了另一个序数问题上,但意识到考虑到它是python,这个问题更适用。

        13
  •  0
  •   alecxe    12 年前

    我必须从javascript转换一个脚本,在那里我有一个复制phps-date-obj的有用fn。非常相似

    def ord(n):
        return str(n)+("th" if 4<=n%100<=20 else {1:"st",2:"nd",3:"rd"}.get(n%10, "th"))
    

    这和我的约会设计师联系在一起:

    def dtStylish(dt,f):
        return dt.strftime(f).replace("{th}", ord(dt.day))
    

    ps-我是从另一个线程得到的,它被报告为一个副本,但它并不完全是因为该线程也解决了日期问题。

        14
  •  0
  •   Michael Swartz    11 年前

    这是我编写的日历类型程序的一部分(我不包括整个程序)的一个函数。它为大于0的任何数字添加正确的序数。我包括一个循环来演示输出。

    def ordinals(num):
        # st, nums ending in '1' except '11'
        if num[-1] == '1' and num[-2:] != '11':
            return num + 'st'
        # nd, nums ending in '2' except '12'
        elif num[-1] == '2' and num[-2:] != '12':
            return num + 'nd'
        # rd, nums ending in '3' except '13'
        elif num[-1] == '3' and num[-2:] != '13':
            return num + 'rd'
        # th, all other nums
        else:
            return num + 'th'
    
    data = ''
    
    # print the first 366 ordinals (for leap year)
    for i in range(1, 367):
        data += ordinals(str(i)) + '\n'
    
    # print results to file
    with open('ordinals.txt', 'w') as wf:
       wf.write(data)