我是新手,
我有这样的名单:
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
...但无法取得进展
感谢你们的帮助。
发布于 2021-05-01 10:45:03
你可能需要在这里使用迭代工具组-
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发布于 2021-05-01 10:41:06
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让我解释一下:
'I',如果是,则返回false。如果不是,则循环遍历列表,每次遇到连续的“I‘s”,就会添加计数器。如果该项不是'I',则将计数器添加到列表中,并将其重置为零。这样我们就能得到一份不允许的名单。对于连续的'I's.out[-1])是否是列表的max值。如果是这样,则返回True,如果不是,则返回Truehttps://stackoverflow.com/questions/67345253
复制相似问题