[英]Consecutive values in a list (python)
我正在尝试查找以下列表是否包含超过 4 个连续值。
小时=[9,10,11,12,13,14,15]
我试过这段代码并返回上面的列表有超过 4 个连续值,但它不适用于其他数字。
hours=[9,28,11,23,13,9,15]
y = sorted(hours)
consecutive_hours = 0
while consecutive_hours <=4:
for hours in hours:
if len(y) == 7 and y[6]-y[0] == 6:
consecutive_hours += 1
else:
break
if consecutive_hours > 4:
print("The list", hours, "contains more than 4 consecutive hours.")
else:
print("The list",hours, "does not contain more than 4 consecutive hours.")
尝试这个!
hours = [9, 28, 11, 23, 13, 9, 15]
y = sorted(hours)
# Starts with 1 consecutive hour, we will subtract later
consecutive_hours = 1
# Check for the number of consecutive hours
for i in range(len(y)):
if y[i] == y[i - 1] + 1:
consecutive_hours += 1
if consecutive_hours == 1: consecutive_hours = 0
# Print results
if consecutive_hours > 4:
print("The list ", hours, " contains more than 4 consecutive hours.")
else:
print("The list ", hours, " does not contain more than 4 consecutive hours.")
你可以试试这样的
hours=[9,28,11,23,13,9,15]
y = sorted(hours)
consecutive_hours = 1
for i in range(0, len(y)):
j = i + 1
if j >= len(y):
break
if y[j] == y[i] + 1:
consecutive_hours += 1
elif consecutive_hours > 4:
break
else:
consecutive_hours = 1
if consecutive_hours > 4:
print("The list", hours, "contains more than 4 consecutive hours.")
else:
print("The list",hours, "does not contain more than 4 consecutive hours.")
以下代码将允许您检查列表中的下一个数字是否是for
循环所在的当前数字的consecutive_hours
数字,如果是,它将向 Continuous_hours 变量添加一。 如果for
循环到达的数字不是前一个数字的consecutive_hours
数字,它将设置 Continuous_hours 为0
。 如果在for
循环遍历整个列表之前, consecutive_hours
变量大于4
,则for
循环将中断,如果在循环到达列表末尾时该值小于或等于4
,则循环将结束. for
循环之后的以下if
语句将检查consecutive_hours
值,并打印相应的语句。
hours=[9,28,11,23,13,14,15,16,17,9,15,1,2,3,4]
y = sorted(hours)
consecutive_hours = 0
for num in hours:
if hours.index(num) == len(hours)-1:
break
elif hours[hours.index(num)+1] == num + 1:
consecutive_hours += 1
if consecutive_hours > 4:
break
else:
consecutive_hours = 0
if consecutive_hours == 4:
print("The list", hours, "contains more than 4 consecutive hours.")
else:
print("The list",hours, "does not contain more than 4 consecutive hours.")
如果不进行排序,您可以使用计数器 class(来自集合)来计算将所有值与其偏移量 0、1、2 和 3 组合时获得的匹配数:
from collections import Counter
def maxConsec(hours,span=4):
counts = Counter(h-i for h in {*hours} for i in range(span))
return span in counts.values()
output:
maxConsec([9,10,11,12,13,14,15]) # True
maxConsec([9,28,11,23,13,9,15]) # False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.