首页 > 解决方案 > 返回特定连续项目的计数

问题描述

我有以下列表, my_list = ['UK', 'FR', 'UK','SP', 'CN', 'USA', 'UK'] 我正在尝试返回最大连续项目后面没有“UK”。

因此,例如,这里的最大连续项目为 3('SP'、'CN'、'USA')

我已经开始了以下操作,但这只会返回没有“UK”的计数。

def country_count(my_list):
    new_country = []
    for country in my_list:
        if country != 'UK':
            new_country.append(country)
        else:
            continue
    return len(new_country)

标签: pythonfunction

解决方案


您只需要一个计数器来存储当前的观察次数并更新最大值,如果找到“UK”则重置该最大值。

my_list = ['UK', 'FR', 'UK','SP', 'CN', 'USA', 'UK'] 

counter, max_val = 0, 0 # counter and max occurences

for idx, item in enumerate(my_list): # traverse the list
    if idx+1 != len(my_list): # if it is not the last element, check next element
        if my_list[idx+1] != 'UK': # check if following element is 'UK'
            counter += 1 # if not 'UK', increment counter
            if counter > max_val: # if current count is greater than previous max, store it
                max_val = counter
        else:
            counter = 0 # reset counter

print(max_val)

推荐阅读