繁体   English   中英

使用列表元素的总和查找列表的索引

[英]Find index of a list using the sum of the list elements

我正在尝试创建一个函数,该函数返回最小元素的索引,该元素沿其所有元素在其左侧的总和大于一个数字x

我该如何用Python的方式做到这一点?

例:

我有号码的列表[32, 6, 12]我试图使,将返回的函数0如果x < 321如果x < 32 + 62 ,如果x < 32 + 6+ 12

一种非Python方式是:

a = [23,3,32]
i = 0
summ = 0
found = False

def example(e):
    while not found: 
        if e <= (a[i] + summ):
            found = True
            element = i
        else:
            summ += a[i]
            i += 1

    return element
def find_index(a, x):
    for i, e in enumerate(a):
        x -= e
        if x < 0:
            return i
    return i

有一个非常好的功能性方法可以做到这一点:

import itertools
import operator

xs = [32, 6, 12]
target = 5

next(i for i, x in enumerate(itertools.accumulate(xs, operator.add)) if x > target)

在列表的最后,它引发StopIteration

找到了不同的解决方案

>>> xs = [18,30,307]
>>> element = 40
>>> target = [sum(xs[:i+1]) for i, elem in enumerate(xs)]
>>> target.index((i for i in target if i>element).next())
1

带过滤器

>>> target.index(filter(lambda x: x > element, target)[0])
1

带过滤器+发电机

>>> import itertools
>>> target.index(itertools.ifilter(lambda x: x > element, target).next())
1

暂无
暂无

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

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