arrays - 如何使用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']
我也需要帮助进行排序
解决方案
第一个问题是您需要将数字转换abc
为int
(如您所做的那样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])]
推荐阅读
- django - 如何使用 Django 在 Elastic Transcoder 中设置作业输出的持续时间?
- java - 从 2.5B 记录中取出 2.14B 记录后,Resultset.next() 没有继续前进,并且在很长一段时间后就存在了
- vue.js - 如何使 Vue 组件的类绑定绑定到内部元素而不是根元素?
- javascript - 在选项“选择”中首先包含选择值。
- javascript - 如何将 window.innerHeight 设置为全尺寸?
- python - Python制表未正确写入文本文件
- android - 在 Android 物理设备上反应原生 axios 发布请求网络错误
- r - 如何在 R 中绘制立方体?
- network-programming - Qt QNetworkConfiguration 和 QNetworkConfigurationManager 类的第 3 方库
- python-3.x - 将 Pillow 中加载的 gif 图像转换为 png