如何计算列表中元素之前的特定元素?

时间:2017-02-21 15:40:25

标签: python list function count formula

我们有一个清单

list = [1, 1, 1, 0, 1, 0, 0, 1] 

我正在尝试找到一个函数来计算每个项目之前0的数量,然后将这个数字乘以3.

def formula(n):
    for x in list:
        if x == 1:
            form = n * 3
            return form
#If x is 1, count the number of zeros right before x and multiply this by 3, 

例如,对于上面的列表,第一个元素是1,并且在它之前没有数字,程序应计算0 * 3 = 0,对于第二个项目,也是1,即之前的数字它也不是零,程序也应该计算0 * 3 = 0.第4个元素是0所以程序应该忽略,对于第5个元素是1,它之前的数字是0,程序到计算1 * 3 = 3,对于第6个元素,它在1之前的数字,系统应该计算0 * 3 = 0.第7个元素是0,因为x不等于1,程序不应该做任何事情。对于最后一个为1的元素,它之前的最后两个数字为零,程序应该计算2 * 3 = 6

3 个答案:

答案 0 :(得分:3)

我相信你正在寻找一个带有简单计数器的发电机:

def get_values (list):
    n = 0
    for x in list:
        if x == 1:
            yield n * 3
            n = 0   # reset the counter
        elif x == 0:
            n += 1  # increment the counter

print(list(get_values([1, 1, 1, 0, 1, 0, 0, 1])))
# [0, 0, 0, 3, 6]

答案 1 :(得分:1)

试试这个,

def formula(l):
    count_zero = 0
    result = []

    for i in l:
        if i == 1:
            result.append(3*count_zero)
            count_zero = 0
        elif i == 0:
            count_zero += 1

    return result

# Test case
l = [1, 1, 1, 0, 1, 0, 0, 1] 
result = formula(l)
print(result)
# [0, 0, 0, 3, 6]

答案 2 :(得分:1)

这是我解决问题的方法。

test_list = [1, 1, 1, 0, 1, 0, 0, 1]


def formula(list):
    track = []
    start = 0

    for i,n in enumerate(list):
        count_list_chunk = list[start:i]
        if count_list_chunk.count(0) > 0 and n != 0:
            start = i

        if n != 0:
            track.append( count_list_chunk.count(0)*3 )

    return track

print formula(test_list)
#[ 0, 0, 0, 3, 6]