首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >计算列表中的连续项

计算列表中的连续项
EN

Stack Overflow用户
提问于 2021-05-01 10:34:21
回答 2查看 54关注 0票数 0

我是新手,

我有这样的名单:

List1= ['I', 'P', 'P', 'I', 'I', 'I', 'I', 'I', 'P', 'I', 'I', 'I']

List2= ['P', 'P', 'P', 'P', 'I', 'I', 'I', 'I', 'P', 'I', 'I', 'P']

List3= ['P', 'P', 'P', 'I', 'I', 'I', 'I', 'P', 'P', 'I', 'I', 'I', 'P', 'I', 'I', 'I', 'I', 'I', 'I']

只有当列表的最后一项是'I‘时,我才想计算连续的'I’。

In our list1 it's 1-5-3, 3 is not greater then 5, so it's not true

In our list2 it will ignore it because the last index is a 'P'

In our list3 it's 4-3-6, 6 is greater then 3 and then 4 so it's True

对于all lists,如果最后一个连续的组更大,那么所有的先例组都会给出True

我试过了,但什么也没给:

代码语言:javascript
复制
n=0
For items in lists1:
 if list1 [-1] == "P":
else:
List1 [n]
n+=1
...

但无法取得进展

感谢你们的帮助。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-05-01 10:45:03

你可能需要在这里使用迭代工具组-

代码语言:javascript
复制
from itertools import groupby

def check_list(l):
    if l[-1] == 'I':
        result = [len(list(g)) for k,g in groupby(l) if k=='I']
        if max(result) == result[-1]:
            return True
    return False

check_list(List1) # False
check_list(List2) # False
check_list(List3) # True
票数 1
EN

Stack Overflow用户

发布于 2021-05-01 10:41:06

代码语言:javascript
复制
def f(l):
    if l[-1] != 'I':
        return False
    else:
        c = 0; out = []
        for index, item in enumerate(l):
            if item == 'I':
                c+= 1
                if index == len(l)-1 and c != 0:
                    out.append(c)
            else:
                if c != 0:
                    out.append(c)
                    c=0                             
        return out[-1] == max(out)
print(f(List1))
print(f(List2))
print(f(List3))

输出:

代码语言:javascript
复制
False
False
True

让我解释一下:

  1. 首先检查最后一项是否为'I',如果是,则返回false。如果不是,则循环遍历列表,每次遇到连续的“I‘s”,就会添加计数器。如果该项不是'I',则将计数器添加到列表中,并将其重置为零。这样我们就能得到一份不允许的名单。对于连续的'I's.
  2. Then,它检查列表的最后一项(out[-1])是否是列表的max值。如果是这样,则返回True,如果不是,则返回True
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67345253

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档