即使列表不能被10整除,也要根据百分比将列表分成四部分。Python

2024-10-01 07:25:56 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我正在处理一个长度未知的列表。我需要把这个单子分成四部分。在

第一部分=清单的前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问题,但我不知道如何去做它,我已经做了好几天了。我会很感激你的帮助。在

谢谢


Tags: 列表lenone单子threefourfivetwo
2条回答

你应该很清楚,用匹配的长度来划分列表是不可能的。但还有另一种方法:

def do_split(x, percent):
    L = len(x)
    idx1 = [0] + list(int(L * p) for p in percent[:-1])
    idx2 = idx1[1:] + [L]
    return list(x[i1:i2] for i1,i2 in zip(idx1, idx2))

splits = [0.2, 0.4, 0.8, 1.0]
print do_split(["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"], splits)
#  -> [['one', 'two'], ['three', 'four'], ['five', 'six', 'seven', 'eight'], ['nine', 'ten']]
print do_split( ["one", "two", "three", "four", "five", "six", "seven"], splits)
#  > [['one'], ['two'], ['three', 'four', 'five'], ['six', 'seven']]

这应该是正确的方法,对于任意数量的任何大小的拆分(不只是四个)(只要它们加起来等于1):

def percentage_split(seq, percentages):
   assert sum(percentages) == 1.0
   prv = 0
   size = len(seq)
   cum_percentage = 0
   for p in percentages:
       cum_percentage += p
       nxt = int(cum_percentage * size)
       yield seq[prv:nxt]
       prv = nxt

(这是一个生成函数,您可以得到四分位列表,如下所示:

^{pr2}$

如果您安装了numpy,它可以更简洁一点:

from numpy import cumsum

def percentage_split(seq, percentages):
    cdf = cumsum(percentages)
    assert cdf[-1] == 1.0
    stops = map(int, cdf * len(seq))
    return [seq[a:b] for a, b in zip([0]+stops, stops)]

如果你只想要四个相等的四分位数。。。在

numpy.split(seq, 4)

相关问题 更多 >