Python对数组进行排序

时间:2016-12-30 14:04:15

标签: python sorting

我试图对包含变量类的numpy数组进行排序。

groups =['(0, 10]', '(10, 20]', '(100, 110]', '(110, 120]', '(120, 130]',
         '(130, 140]', '(140, 150]', '(150, 160]', '(160, 170]', '(170, 180]', 
         '(180, 190]', '(190, 200]', '(20, 30]', '(200, 210]', '(210, 220]', 
         '(230, 240]', '(30, 40]', '(40, 50]', '(50, 60]', '(60, 70]', 
         '(70, 80]', '(80, 90]', '(90, 100]']

我想要这个:

groups = ['(0, 10]', '(10, 20]','(30, 40]','(40, 50]', '(50, 60]', ...]

我试过了:

sort(groups)

但没什么........

3 个答案:

答案 0 :(得分:3)

排序功能为 Dim cache As Dictionary(Of Long, Double(,)) = New Dictionary(Of Long, Double(,)) Public ReadOnly Property Thing(i as long) as double(,) Get Dim result As Double(,) If Not cache.TryGetValue(i, result) Then result = SomeCalculation(i) cache.Add(i, result) End If Return result End Get End Property 。我们将使用一个键函数来提取数字并将它们转换为整数元组。

sorted

输出:

sorted(groups, key=lambda x: tuple(map(int, x[1:-1].split(','))))

答案 1 :(得分:1)

你必须将你的字符串解释为数字元组,否则它们将按字典顺序排序(这会产生错误的结果!):

struct obj
{
    int n;

    operator int&() { return n; }
};

int tail_impl(obj*& n)
{
    int n1 = *n + 1 > 1000 ? *n - 1000 : *n + 1;
    delete n;
    n = new obj{n1};
    return tail_impl(n);
}

int tail(obj n)
{
  obj *n1 = new obj{n};
  auto ret = tail_impl(n1);
  delete n1;
  return ret;
}

int main()
{
    tail(obj{ 1 });
}

返回:

def interpret_as_tuple(x):
    splitted = x.split(',')
    first = int(splitted[0].strip('( '))
    second = int(splitted[1].strip('] '))
    return first, second

groups.sort(key=interpret_as_tuple)

groups

答案 2 :(得分:-3)

您的元素存在两个问题

  • 他们是字符串,而不是数字元组
  • 结束]与开场不符(

所以,你首先必须转换它们

groups = [eval(group[:-1] + ')') for group in groups]
print(sorted(groups))