首页 > 解决方案 > 如何使用python中的split函数按降序拆分数组列表?

问题描述

我正在尝试从用户获取数组输入并将数组拆分为子数组,每个子数组有 3 个元素。如果不。数组中的元素不能被 3 整除,我想将较小数组的大小从第一个子数组增加 1。

我尝试使用 split 函数,但这给了我按递增顺序排列的子数组。我希望它按降序排列。

import numpy as np
def array_list(x):

  original_list = []
  for i in range (0,x):
    abc = input("Enter element: ")
    original_list.append(abc)
  original_list.sort()
  return(original_list)

x = int(input("Enter no. of elements: "))
Input = array_list(x)
print("Input = ",Input)
print("Output = ",np.split(Input,[3]))

我的代码执行如下::

Input =  ['11', '13', '15', '23', '34', '7', '77']  
Output =  [array(['11','13','15']),array(['23','34','7','77']]

我希望我的输出为:

Input =  ['11', '13', '15', '23', '34', '7', '77']    
Output = [array(['11','13','15',23], array(['34','7', '77']  

我也需要帮助进行排序

标签: arrayspython-3.xnumpysplit

解决方案


第一个问题是您需要将数字转换abcint(如您所做的那样x)以对数字进行排序。要根据需要拆分数组,您可以在拆分之前反转数组。

import numpy as np


def array_list(x):
    original_list = []
    for i in range(0, x):
        abc = int(input("Enter element: "))
        original_list.append(abc)
    original_list.sort(reverse=True)
    return original_list


x = int(input("Enter no. of elements: "))
Input = array_list(x)
print("Input = ", Input)
Output = np.array_split(Input, int(x/3)) if x >= 3 else Input
print("Output = ", Output)
# test 1
Enter no. of elements: 7
Input =  [77, 34, 23, 15, 13, 11, 7]
Output =  [array([77, 34, 23, 15]), array([13, 11,  7])]

# test 2
Enter no. of elements: 8
Input =  [77, 45, 34, 23, 15, 13, 11, 7]
Output =  [array([77, 45, 34, 23]), array([15, 13, 11,  7])]

# test 3
Enter no. of elements: 9
Input =  [99, 77, 45, 34, 23, 15, 13, 11, 7]
Output =  [array([99, 77, 45]), array([34, 23, 15]), array([13, 11,  7])]

推荐阅读