【问题标题】:Python sort array by another positions arrayPython按另一个位置数组排序数组
【发布时间】:2013-12-30 04:16:51
【问题描述】:

假设我有两个数组,第一个包含 int 数据,第二个包含位置

a = [11, 22, 44, 55]

b = [0, 1, 10, 11]

即我希望将 a[i] 移动到位置 b[i] for all i。如果我没有指定位置,那么插入一个-1

sorted_a = [11, 22,-1,-1,-1,-1,-1,-1,-1,-1, 44, 55]
            ^   ^                            ^   ^
            0   1                            10  11

另一个例子:

a = [int1, int2, int3]

b = [5, 3, 1]

sorted_a = [-1, int3, -1, int2, -1, int1]

这是我尝试过的:

def sort_array_by_second(a, b):

   sorted = []

   for e1 in a:
      sorted.appendAt(b[e1])

  return sorted

我显然搞砸了。

【问题讨论】:

  • ab 的长度相同,不是吗?
  • 是的,它们的长度总是相同的。我也在使用基于 0 的索引

标签: python arrays sorting


【解决方案1】:

类似这样的:

res = [-1]*(max(b)+1)   # create a list of required size with only -1's

for i, v in zip(b, a):
    res[i] = v 

算法背后的想法:

  1. 创建结果列表,其大小能够容纳b 中的最大索引
  2. 使用-1 填充此列表
  3. 遍历b元素
  4. res[b[i]] 中的元素设置为正确的值a[i]

这将在除b 中包含的索引之外的每个位置留下带有-1 的结果列表,它们的对应值将是a

【讨论】:

  • 我认为你只是想从b 导出排序,值无关紧要
  • 再想一想 - 也许“我希望将 a[i] 移动到所有 i 的位置 b[i]”意味着你是对的
  • 很抱歉,我不太了解您。 OP对算法不是很清楚,我只是试图向他说明一种方法。
  • 您好,感谢您的快速回复。我得到一个IndexError: tuple index out of range
【解决方案2】:

我会使用自定义key 函数作为参数进行排序。这将根据另一个列表中的相应值对值进行排序:

to_be_sorted = ['int1', 'int2', 'int3', 'int4', 'int5']
sort_keys = [4, 5, 1, 2, 3]

sort_key_dict = dict(zip(to_be_sorted, sort_keys))

to_be_sorted.sort(key = lambda x: sort_key_dict[x])

这样做的好处是不将 sort_keys 中的值视为有效的整数索引,这不是一个非常稳定的东西。

【讨论】:

    【解决方案3】:
    >>> a = ["int1", "int2", "int3", "int4", "int5"]
    >>> b = [4, 5, 1, 2, 3]
    >>> sorted(a, key=lambda x, it=iter(sorted(b)): b.index(next(it)))
    ['int4', 'int5', 'int1', 'int2', 'int3']
    

    【讨论】:

      【解决方案4】:

      Paulo Bu 的回答是最好的 Pythonic 方式。如果您想坚持使用像您这样的功能:

      def sort_array_by_second(a, b):
         sorted = []
         for n in b:
            sorted.append(a[n-1]) 
        return sorted
      

      会成功的。

      【讨论】:

        【解决方案5】:

        按 B 的值对 A 进行排序:

        A = ['int1', 'int2', 'int3', 'int4', 'int5']
        B = [4, 5, 1, 2, 3]
        
        from operator import itemgetter
        C = [a for a, b in sorted(zip(A, B), key = itemgetter(1))]
        
        print C
        

        输出

        ['int3', 'int4', 'int5', 'int1', 'int2']
        

        【讨论】:

          【解决方案6】:
          a = [11, 22, 44, 55] # values
          b = [0, 1, 10, 11]  # indexes to sort by
          
          sorted_a = [-1] * (max(b) + 1)
          for index, value in zip(b, a):
              sorted_a[index] = value
          
          print(sorted_a)
          # -> [11, 22, -1, -1, -1, -1, -1, -1, -1, -1, 44, 55]
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-03-19
            • 2016-01-15
            • 2018-11-19
            • 2023-03-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-02-10
            相关资源
            最近更新 更多