所以我正在处理一个长度未知的列表。我需要把这个单子分成四部分。在
第一部分=清单的前20%
第二部分=从清单的20%到40%
第三部分=从清单的40%到80%
第四部分=从列表的80%到100%。在
现在的问题是,如果列表中的元素少于10个,那么我的一些列表将是空的。我的问题是如何避免这个问题。
这是我现在的脚本:
x = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"]
twentyPercentOne = len(x) * 0.2
twentyPercentTwo = len(x) * 0.4
fourtyPercentThree = len(x) * 0.8
i = 0
j = 2
m = []
while j < (twentyPercentOne + 1):
m.append(x[i:j])
i = (i + 2)
j = (j + 2)
h = []
while j < (twentyPercentTwo + 1):
h.append(x[i:j])
i = (i + 2)
j = (j + 2)
l = []
while j < (fourtyPercentThree + 1):
l.append(x[i:j])
i = (i + 2)
j = (j + 2)
t = x[i:len(x)]
输出:
^{pr2}$如果列表长度小于10,则输出: x=[“一”,“二”,“三”,“四”,“五”,“六”,“七”]
[['one', 'two']]
[]
[['three', 'four'], ['five', 'six']]
['seven']
有人知道怎么做吗?我知道它更像是一个数学问题而不是一个python问题,但我不知道如何去做它,我已经做了好几天了。我会很感激你的帮助。在
谢谢
你应该很清楚,用匹配的长度来划分列表是不可能的。但还有另一种方法:
这应该是正确的方法,对于任意数量的任何大小的拆分(不只是四个)(只要它们加起来等于1):
(这是一个生成函数,您可以得到四分位列表,如下所示:
^{pr2}$)
如果您安装了numpy,它可以更简洁一点:
如果你只想要四个相等的四分位数。。。在
相关问题 更多 >
编程相关推荐