繁体   English   中英

Python将列表划分为百分比

[英]Python divide list into percentages

我有一个函数,可以将随机颜色应用于按百分比定义的每组元素。 在这种情况下,我有一个包含 154 个元素的列表,但不知何故最终我只得到了 152 个已处理的元素。 不知道为什么,因为我在最后调用函数时总共给了它 100%。

import maya.cmds as cmds
import random

def selector(percents):
    RandomSelection = []
    mySel = cmds.ls(sl=1) # a list of elements with a total of 154
    random.shuffle(mySel)
    
    start = 0
    for cur in percents:
        end = start + cur * len(mySel) // 100
        RandomSelection.append(mySel[start:end])
        start = end
    
    print(len(mySel)) # 154
    print ( sum( [ len(listElem) for listElem in RandomSelection]) ) # 152 # why not 154?
    
    for mesh in RandomSelection:
        r = [random.random() for i in range(3)]
        cmds.polyColorPerVertex(mesh,rgb=(r[0], r[1], r[2]), cdo=1 )
    

selector([70, 10, 15, 5])
#154
#152

谢谢你。

end = start + cur * len(mySel) // 100在每次迭代中最多可以删除 1 个元素。

试试这个:

start = 0
cumul = 0
for cur in percents:
    cumul += cur
    end = cumul * len(mySel) // 100
    RandomSelection.append(mySel[start:end])
    start = end

由于花环,这仍然会在每次迭代中最多下降 1,但这些下降不会累积(因为你从新鲜重新计算你的end ),最后你保证有一个精确的划分,所以用完所有元素.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM