如何根据时间对一串数字进行排序?

时间:2017-10-31 16:12:48

标签: python string sorting time numbers

我现在拥有的是:

a=["2013-11-20,29,0,0","2013-11-20,3,0,2"],

其中a[1]是一天中的a[1] 5分钟,a[3]a[4]是计数。

我想通过前两个元素对此进行排序。 但是当我使用sort时,a[0]始终排在第一位。 事实上,我希望a[1]先来。我该怎么做? 我在key中尝试了sort参数。例如,a.sort(key=int),出现错误,说明基数为10的int()的无效文字:' 2013-11-20,29,0,0'

2 个答案:

答案 0 :(得分:0)

您的问题是,列表中的每个项目都是字符串。如果对字符串进行排序,则每个位置的每个字符将相互比较。在您的示例中,所有字符在第一个逗号之后都是相同的。在逗号之后,下一个字符是'2'和'3'。作为'3'>'2',排序不是您想要的。我假设你想要29岁> 3。

在这种特殊情况下,您可以反转排序

a.sort()
a.reverse()

但是,由于您可能有一个包含更多项目的列表,这将无效......我看到的唯一解决方案是将逗号','中的每个项目拆分为。然后将应该被视为整数的项转换为int。例如,您可以这样做:

a=["2013-11-20,29,0,0","2013-11-20,3,0,2"]

a_temp=[]
for item in a:
    splitstr = item.split(',')
    i=0
    temp = []
    for elem in splitstr:
        if i>0:
            temp_i=int(elem)
        else:
            temp_i=elem
        temp.append(temp_i)    
        i+=1

    a_temp.append(temp)

您的临时列表现在看起来像这样:

[['2013-11-20',29,0,0],['2013-11-20',3,0,2]]

然后根据您的意愿按位置排序。你可以这样做:

from operator import itemgetter

a_temp_sorted=sorted(a_temp, key=itemgetter(0,1,2,3))

通过使用itemgetter,您可以定义要排序的顺序。这里首先按元素0,然后是1等排序......但是你可以改变顺序。 a_temp_sorted现在看起来像:

[['2013-11-20',3,0,2],['2013-11-20',29,0,0]]

现在您可以将结果再次转换为字符串。你可以这样做:

a_sorted=[]
for item in a_temp_sorted:
    newstring=''
    i=0
    for elem in item:
        if i>0:
            temp_i=str(elem)
            newstring+=','+temp_i
        else:
            newstring+=elem
        i=1
    a_sorted.append(newstring)

a_sorted现在是您的源a的排序版本。它现在看起来像这样:

['2013-11-20,3,0,2','2013-11-20,29,0,0']

答案 1 :(得分:0)

创建一个返回要排序的值元组的键函数。

import datetime
a=["2013-11-20,29,0,0","2013-11-20,3,0,2"]
def f(thing):
    #separate the values
    a,b,c,d = thing.strip().split(',')
    # turn one into a datetime.date
    y, m, d = map(int, a.split('-'))
    a = datetime.date(y, m, d)
    # turn the others into ints
    b,c,d = map(int, (b,c,d))
    # return the values in order of precedence
    return (a,b,c,d)

然后用它来对列表进行排序

a.sort(key = f)