python将数组拆分为等效级别的子数组 [英] python split array into sub arrays of equivalent rank
问题描述
已编辑
我有一个 n 个排序值的数组.
I have an array of n sorted values.
我想创建 m 子数组,以便将最好的元素放入第一个子数组,将第二个元素放入第二个子数组,依此类推,并且我的 n + 1个 最佳元素进入了我的第一个子数组.
I want to create m sub-arrays so that my best element goes into my first sub-array, my second element goes into my second sub array, etc, and my n+1-th best element goes into my first sub array.
如果我只有两个数组,那很容易,但是如果我想要两个以上的子数组,我不知道该怎么做.
If I have just two arrays its easy but if I want more than two sub-arrays I don't know how to do it.
例如,如果我有一个初始数组:
for example if I have an initial array:
a = [50, 45, 40, 35, 30, 25, 20, 10, 9, 8]
我想要3个子阵列:
x1: [50, 35, 20, 8]
x2: [45, 30, 10]
x3: [40, 25, 9]
最有效/最有效的方法是什么?
What's the most efficient/pythonic way of doing this?
推荐答案
FOR X SUBLISTS:
一种可能是:
def get_sublists(original_list, number_of_sub_list_wanted):
sublists = list()
for sub_list_count in range(number_of_sub_list_wanted):
sublists.append(original_list[sub_list_count::number_of_sub_list_wanted])
return sublists
然后您可以解压缩存储在 sublist
中的子列表.
You can then unpack the sub-lists stored in sublist
.
例如:
a = [5,4,3,2,1,0]
x1, x2 = get_sublists(a, 2)
将为您提供预期的输出.
will grant you the expected output.
这是简单的解决方案.在itertools或其他lib中,它们可能更像pythonic.
This is the trivial solution. Their is probably something more pythonic in itertools or an other lib.
如果您不了解此代码的工作原理,请查看 查看全文