以正确的顺序对时间间隔进行排序

时间:2019-06-27 09:05:28

标签: python pandas numpy intervals

rigt现在我有了此间隔列表

test = ['(0.556, 1.389]', '(0.192, 0.386]', '(0.386, 0.556]', '(-0.759, -0.401]', '(-0.401, -0.064]', '(-0.064, 0.192]', '(-1.34, -0.759]']

我想按正确的顺序对它们进行排序,我尝试了以下代码:

test.sort()
sorted(test, key=lambda l:l[0])

但是结果不正确:

test = ['(-0.064, 0.192]', '(-0.401, -0.064]', '(-0.759, -0.401]', '(-1.34, -0.759]', '(0.192, 0.386]', '(0.386, 0.556]', '(0.556, 1.389]']

我只是想要一个按顺序排序的列表,像这样:

test = ['(-1.34, -0.759]', '(-0.759, -0.401]', '(-0.401, -0.064]', '(-0.064, 0.192]', '(0.192, 0.386]', '(0.386, 0.556]', '(0.556, 1.389]']

1 个答案:

答案 0 :(得分:4)

如评论中所述,您的列表元素是字符串。解决您的问题的一种方法是将它们转换为元组,然后对元组列表进行排序:

def board():
    grid0 = []
    grid1 = []
    a = 0
    b = 0
    c = 0

    while a < 8:
        grid0.append("0")
        a += 1

    while b < 8:
        grid1.append(grid0.copy())
        b += 1

    while c < 5:
        grid1[random.randint(0,7)][random.randint(0,7)] = "B"
        c += 1

    for row in grid1:
        print(row)

此代码段包含您的列表,将每个字符串末尾的import ast test = ['(0.556, 1.389]', '(0.192, 0.386]', '(0.386, 0.556]', '(-0.759, -0.401]', '(-0.401, -0.064]', '(-0.064, 0.192]', '(-1.34, -0.759]'] new_list = [] for x in test: a = x.replace(']', ')') b = ast.literal_eval(a) new_list.append(b) new_list = sorted(new_list, key=lambda l:l[0]) print(new_list) # [(-1.34, -0.759), (-0.759, -0.401), (-0.401, -0.064), (-0.064, 0.192), (0.192, 0.386), (0.386, 0.556), (0.556, 1.389)] 替换为],然后利用)库(请参见example)将带有ast的字符串转换为实际的元组,并将其附加到新列表中。 随后,它会按照您在问题中提出的建议应用literal_eval