【问题标题】:Python -- Find a sequence of numbers in triplets, quadruplets or more:Python -- 查找三胞胎、四胞胎或更多的数字序列:
【发布时间】:2021-01-18 14:05:20
【问题描述】:

所以,在我的问题中,我有一个数字列表,即:

[0, 10, 11, 12, 24, 26, 28, 30, 31]

我想在这个列表中找到一个连续数字的序列,在这种情况下 [10, 11, 12] 我想要的输出是一个元组,告诉我这个序列中第一个数字的位置以及有多少个数字序列,泛化为 N 个数的序列。

给定序列的输出等于 (2,3)

我尝试过类似 3 的序列:

#sequence of 3
for i in range(len(b)-3):
  if i>=2 and b[i]==b[i+1] and b[i]==b[i+2] and b[i]!=b[i-1] and b[i]!=b[i+3]:
    count_seq_3 += 1
    position_3= i
 print(position_3, count_seq_3)  

给定的输出是 (0,0) 任何人都可以帮我解决什么问题吗?提前谢谢!!

【问题讨论】:

    标签: python list numbers sequence


    【解决方案1】:
    list = [0, 10, 11, 12, 24, 26, 28, 30, 31]
    sequence = []
    for i in range(len(list)-2):
        if list[i] == list[i+1] - 1 or list[i] == list[i-1] + 1:
            sequence.append(list[i])
    print((list.index(sequence[0]), len(sequence)))
    

    实际输出为:

    (1, 3)
    

    其中 1 是列表中起始元素 10 的索引,3 是序列的长度。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-13
      • 1970-01-01
      • 1970-01-01
      • 2012-10-27
      • 2017-04-11
      • 1970-01-01
      相关资源
      最近更新 更多