我不知道为什么我的短块代码不起作用

问题描述 投票:0回答:1
中的嵌套列表

如果有3个以上的序列+1高于上一个数字。 (例如:[3,4,5,6])然后,它只能成为前3个数字的三联组。 ([3,4,5])

    如果有可能有多个三胞胎(例如:[3,4,5,6,7,8]),它必须成多组。在这种情况下[[3,4,5],[6,7,8]]保存在winning_triplets
  • 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)
  • 我期望输出为: [[8,9,10],[20,21,22],[23,24,25]]

    ,输出为:[[30],[30],[30]]
您的代码不断清除相同的列表,并将其添加到
triplet

中。您需要一个不同的列表:

winning_triplet

python list
1个回答
-1
投票
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)

按要求输出
    
	

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.