【问题标题】:Calculate consecutive items in a list计算列表中的连续项目
【发布时间】:2021-07-24 11:13:18
【问题描述】:

我是新手,

我有这样的列表:

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

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

n=0
For items in lists1:
 if list1 [-1] == "P":
else:
List1 [n]
n+=1
...

但无法进步

感谢您的帮助 谢谢大家

【问题讨论】:

  • 你有没有尝试过?你到底卡在哪里了?
  • 我试过了,是的,现在我编辑了我的帖子,但我无法进步,谢谢

标签: python list foreach


【解决方案1】:

你可能想在这里使用 itertools groupby -

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

【讨论】:

    【解决方案2】:
    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))
    

    输出:

    False
    False
    True
    

    让我解释一下:

    1. 首先检查最后一项是否为'I',如果是则返回false。
    2. 如果不是,则循环遍历列表,每次遇到连续的 'I' 时,都会添加计数器。如果项目 not 'I' 则计数器被添加到列表中并重置为零。这样我们就得到了一个没有的列表。连续的'I's。
    3. 然后它检查列表的最后一项(out[-1])是否是列表的max 值。如果是,则返回True,如果不是,则返回False

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-05
      • 2016-03-03
      • 2020-02-19
      • 2017-12-26
      • 1970-01-01
      • 1970-01-01
      • 2017-01-13
      相关资源
      最近更新 更多