[英]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.