如果有3个以上的序列+1高于上一个数字。 (例如:[3,4,5,6])然后,它只能成为前3个数字的三联组。 ([3,4,5])
nums = [5, 8, 9, 10, 11, 20, 21, 22, 23, 24, 25, 30]
triplet = []
winning_triplets = []
for i in range(0, len(nums)):
if i == 0:
triplet.append(nums[i])
elif nums[i] != nums[i-1] + 1: #if the current number is not +1 higher than the previous number
triplet.clear()
triplet.append(nums[i])
elif nums[i] == nums[i-1] + 1: #if the current number is +1 higher than the previous number
triplet.append(nums[i])
if len(triplet) == 3:
winning_triplets.append(triplet)
triplet.clear()
print(winning_triplets)
,输出为:[[30],[30],[30]]
您的代码不断清除相同的列表,并将其添加到
triplet
中。您需要一个不同的列表:
winning_triplet
nums = [5, 8, 9, 10, 11, 20, 21, 22, 23, 24, 25, 30]
triplet = []
winning_triplets = []
for i in range(0, len(nums)):
if i == 0:
triplet.append(nums[i])
elif nums[i] != nums[i-1] + 1: #if the current number is not +1 higher than the previous number
triplet = []
triplet.append(nums[i])
elif nums[i] == nums[i-1] + 1: #if the current number is +1 higher than the previous number
triplet.append(nums[i])
if len(triplet) == 3:
winning_triplets.append(triplet)
triplet = []
print(winning_triplets)
按要求输出