我得到了一个清单:
<a href="{{ url('productDetail/ ' . $product->id . '/' . $product->pro_name .') }}">
我想编写一个程序,以检查我的列表中是否存在连续出现5次(该数字可能会因用户输入而异)的数字,然后返回该数字。
在这种情况下,输出应为4。
Python中是否有解决这些问题的预定义函数?
答案 0 :(得分:4)
您可以像这样使用itertools.groupby()
:
from itertools import groupby
lst = [1 , 0 , 4 , 4 , 4 , 4 , 4 , 1]
for number, sublist in groupby(lst):
if len(list(sublist)) == 5:
print(number)
默认情况下,groupby()
根据相等性对连续元素进行分组,因此对您来说效果很好(否则,可以提供key
参数)。
在遍历lst
时,groupby()
函数将构造一个新的子列表,并使用彼此相等的所有连续值填充该子列表。如果迭代值与上一个值不同,则groupby()
将产生number
并填充相应的sublist
。即:(1, [1])
,(0, [0])
,(4, [4, 4, 4, 4, 4])
,最后是(1, [1])
。因此,您只需要检查产生的len()
中的sublist
,以验证它包含足够的元素。请注意,这些实际上不是“列表”,而是“可迭代”,因此需要对list()
进行调用。
答案 1 :(得分:0)
尝试此列表理解:
{
"type": "AdaptiveCard",
"body": [
{
"type": "Image",
"style": "Person",
"url": "data:image/png;
"size": "Small",
"id": "image",
"horizontalAlignment": "Center"
},
{
"type": "TextBlock",
"size": "Medium",
"weight": "Bolder",
"text": "FTP Creation Card",
"id": "title",
"horizontalAlignment": "Center"
},
{
"type": "ColumnSet",
"columns": [
{
"type": "Column",
"items": [
{
"type": "FactSet",
"facts": [
{
"title": "Fill in all the fields",
"value": "with customer data"
},
{
"title": "Click Submit",
"value": "and wait notification to your email"
}
],
"id": "Exploration"
}
],
"width": "stretch"
}
]
},
{
"type": "Input.Text",
"placeholder": "First Name",
"id": "Name"
},
{
"type": "Input.Text",
"placeholder": "Last Name",
"id": "LastName"
},
{
"type": "Input.Text",
"placeholder": "Nickname",
"id": "Login"
},
{
"type": "Input.Text",
"placeholder": "Customer Email address",
"id": "Email"
},
{
"type": "Input.Text",
"placeholder": "Company Name",
"id": "Company"
},
{
"type": "Input.Text",
"placeholder": "Manager",
"id": "Manager"
},
{
"type": "Input.Text",
"placeholder": "Optional : employees",
"id": "InternalUsers"
}
],
"actions": [
{
"type": "Action.Submit",
"title": "Sumbit",
"style": "positive",
"id": "submit"
}
],
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"version": "1.0"
}
输出:
print([v for i, v in enumerate(lst, 1) if {v} == set(lst[i:i+4])])
答案 2 :(得分:0)
Sliding window
解决此问题。
def checkList(listi, num):
k = [listi[0]]
nk = 0
listo = []
for v in listi[1:]:
if v == k[-1]:
k.append(v)
else:
if len(k) == num:
listo.append(k[-1])
k = [v]
if len(k) == num:
listo.append(k[-1])
return listo
l = [1 , 0 , 4 , 4 ,4, 4 , 4 , 1]
print(checkList(l, 5))
答案 3 :(得分:0)
y=list(set([x[i-1] for i in range(n-1, len(x)) if x[i-n:i]==[x[i-n]]*n]))
其中
n-您要寻找的连续出现次数
x-列表,您输入
y-连续出现n次的元素列表