繁体   English   中英

按特定值拆分列表,直到仅保留第一个元素 python

[英]Split a list by certain value until only the first element remains python

我想计算我可以将一组元素除以某个值多少次,直到只剩下一个元素

10 个元素的数组可以除以 3 次,但我的循环只执行一次然后停止。 显然我错过了一些东西..

# a function that takes an integer as input
def split_a_list(length):
    
    # create an array of elements where the input to the function determines the length of the array
    elements = list(range(1, (length +1)))
    begin_index = 0
    end_index = len(elements)-1
    count = 0
    
    # a value that specifies the size of remaining size of the array
    divider = 2 
    
    while begin_index < end_index:
        # because divider = 2 (as defined above), this divides the array in half
        mid_index = math.floor(float((begin_index + end_index)/divider))
        
        # this counts the number of times the array has been divided
        count += 1
        
        # the last index of the array is now the mid index of the previous array
        end_index = mid_index - 1
        
        # here I would like the function to be called again, but with the integer corresponding to
        # the the updated end index which is the mid index of the previous array
        
        return split_a_list(end_index), count


# An array of 10 elements can be divided in half 3 times until 1 element remains
# I would like the function to store the number of times the array can be divided in the variable count 
# and return this value as output


length = 10
split_a_list(length)

这返回 ((None, 1), 1) 但我希望它返回 3,因为 10 的数组可以被划分 3 次,直到剩下 1 个元素

提前非常感谢!

如果您只是在寻找 integer,请保持简单,使用地板除法。

length = len(your_list)
n = 0
while length > 1:
    length //= 2
    n += 1

//运算符 ( floor division ) 在这里用于将length分成 2 个(整体)部分。 然后将地板除法的结果分配回length并继续操作,直到length等于1

你可以看到它在这里工作:

>>> length = 10
>>> length //= 2
5
>>> length //= 2
2
>>> length //= 2
1

暂无
暂无

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

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