简体   繁体   English

如果列表中的最后n个元素大于一个数字,则返回列表中的剩余项

[英]Return remaining items in list, if last n elements in list greater than a number

Given a list of numbers: 给定数字列表:

ar =[1,2,3,4,5,6,7,8,9,10]

I need to find the remaining part of the list if the last n numbers summed are greater than a given number. 如果最后的n个数字之和大于给定的数字,我需要找到列表的其余部分。 For example if the given number was 25, the returned\\"remainder" list would be [1,2,3,4,5,6,7] , since that the last 3 elements add up to 27. 例如,如果给定数字为25,则返回的“剩余”列表将为[1,2,3,4,5,6,7] ,因为最后3个元素的总和为27。

I have some code, but I get the overbearing suspicion that it is quite inefficient, failing that, overly verbose given the simple nature of the task. 我有一些代码,但是我很霸道地怀疑它效率很低,否则,鉴于任务的简单性质,它过于冗长。

def kp_find(ar, level):

    kp1=[]    
    for k in range(len(ar)): #this is required as in reality there is some
        kp1.append(k)        #work to be done within this loop 

    kp_fin = sorted(kp1,reverse = True)

    kp2=[]
    for k in kp_fin:
        kp2.append(k)
        sm_it = sum([i for i in kp2])
        if sm_it>level:
            place = [i for i, j in enumerate(kp_fin) if j == k]
            break
        else:
            place = []

    if place:
        return kp_fin[place[0]:len(kp1)]

print kp_find(ar,24)

As you see it's quite a lot of code for something so insignificant; 如您所见,对于如此微不足道的东西,有很多代码。 any help welcome. 任何帮助欢迎。

It does seem like a lot of code for a simple task. 对于一个简单的任务,似乎确实有很多代码。 You could just pop off elements from the right end of the list until the condition is met. 您可以从列表的右端弹出元素,直到满足条件为止。 Something like this: 像这样:

>>> def kp_find(ar, level):
...     result = ar[:]
...     sum_ = 0
...     while sum_ < level:
...         sum_ += result.pop()
...     return result
... 
>>> kp_find([1,2,3,4,5,6,7,8,9,10], 25)
[1, 2, 3, 4, 5, 6, 7]

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

相关问题 在列表中找到连续数字大于“ n”的最后一个数字 - find the last number in list with consecutive number of numbers greater than “n” 如果列表中的元素数大于 2,则将列表前半部分中的 n 个元素与列表另一半中的元素组合 - Combine n elements in first half of list with elements in other half of a list, if number of elements in a list is greater than 2 当 n 大于列表中元素的数量时,旋转列表 n 次 - Rotating a list n times when n is greater than the number of elements in list 提取所有大于 'm' 且小于 'n' 的列表元素 - Extract all the list elements that are greater than 'm' and less than 'n' 返回列表中大于某个值的项目列表 - Return list of items in list greater than some value 如果日期间隔大于N秒,则使用最后一个值填充列表 - Fill list with last value if date gap is greater than N seconds 如何将列表分成 4 个一组,其中第一个元素大于最后一个? - How to split a list into groups of 4 where first elements are greater than the last? 返回数字大于列表中前一个数字的次数 - Return amount of times a number is greater than previous number in a list Python-如何生成大小大于列表元素个数的排列 - Python - How to generate permutations of size greater than the number of list elements Python 列表中元素的总和大于任何数字 - Python sum of elements in list greater than any number
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM