简体   繁体   English

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

[英]How to count specific elements before an element in a list?

We have a list 我们有一个清单

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

I am trying find a function that would count the number of 0's before each item and then multiply this number by 3. 我正在尝试找到一个函数,该函数将对每个项目之前的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, 

For example for the list above, the first element is a 1 and there are no numbers right before it, the program should compute 0 * 3 = 0, for the second item, which is also a 1, the number right before it is also not a zero, the program should also compute 0 * 3 = 0. The 4th element is 0 so the program should ignore, For the 5th element which is a 1, the number right before it is a 0, the programme to compute 1 * 3 = 3, for the 6th element the number right before it is a 1, the system should compute 0 * 3 = 0. The 7th element is a 0, since x is not equal to 1 the program should not do anything. 例如,对于上面的列表,第一个元素是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,程序不应执行任何操作。 For the last element which is a 1, the last two numbers before it are zeros, the program should compute 2 * 3 = 6 对于最后一个元素为1,最后两个数字为零,则程序应计算2 * 3 = 6

I believe you are looking for a generator, with a simple counter: 我相信您正在寻找带有简单计数器的发电机:

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]

Try this, 尝试这个,

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]

Here is my solution for the problem. 这是我针对该问题的解决方案。

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]

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

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