我有一个无法解决的挑战:
Create a function that accepts a single array as an argument. Given an array of integers, x, sort x and split the integers into three smaller arrays of equal length. If the length of x is not evenly divisible by three, increase the size of the smaller arrays by one starting from the first array. The function should return an array of arrays. Example: # myArry = [2,1,3,4,7,5,9,6,8,13,12,11,10,0,15,16,14] # Output = [ [0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16] ] –
我有一个解决方案,如果数组长度不大于 3,它就不起作用。我也觉得有一种更短的写法。
a = [2,1,3,4,7,5,9,8,12,11,10,0,15,16,14]
b = [2,1,3,4,7,5,9,8,12,11,10,0,15,16]
c = [2,1,3,4,7,5,9,8,12,11,10,0,15]
d = [1]
def myfunc(ar):
length = len(ar)
s = sorted(ar)
n3 = length//3
if(length % 3 == 0):
return [s[index:index+n3] for index in range(0, length, n3)]
else:
num = (len(b) // 3 +1)
A, B, C = [s[index:index+num] for index in range(0, length, num)]
if(len(C) != len(A)):
C.append(C[-1]+1)
return A,B,C
return s
print(myfunc(a))
print(myfunc(b))
print(myfunc(c))[cannot split an array with a length less than 3 by n][1]
示例:
输入
myArry = [2,1,3,4,7,5,9,6,8,13,12,11,10,0,15,16,14]
输出
[ [0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16] ]
最佳答案
在您的帮助下,我找到了可行的解决方案!
import numpy as np
def myfunc(ar):
splited = np.array_split(sorted(ar), 3)
A,B,C = [x.tolist() for x in splited]
if(len(C) != len(A)):
C.append(C[-1]+1)
if(len(C) != len(B)):
B.append(B[-1]+1)
return A,B,C
感谢@igorkf
关于python - 取一个数组并返回 3 个相等的数组,如果该数组不能被 3 整除,则增加较小数组的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58886868/