【问题标题】:how to grab next-in-line integers from list python如何从列表python中获取下一个整数
【发布时间】:2022-08-15 13:41:26
【问题描述】:

所以我有这两个列表:

list1 = [81, 68, 53, 28, 19, 7, 2, 0]

list1 很好,不需要发生任何事情,因为列表中的任何数字都没有数字(上 1 或下 1)。

list2 = [68, 67, 53, 21, 20, 19, 9, 7, 1, 0]

而在 list2 我有 (68,67) (21,20,19) & (1,0)

我怎样才能用“额外”(从高位开始)下一行数字填充新列表?

这可能很重要,也可能不重要,但只是指出 list2 在到达下面的代码之前总是从高到低排序。

这是我到目前为止所得到的:

####################################################
list2 = [68, 67, 53, 21, 20, 19, 9, 7, 1, 0]
numbs_list= []
complete = False
i = 0
# start = 0
# end = len(list2) -1
while complete is False:
    if len(list2) > 1:
        # if index 1 is next-in-line to index 0
        # if 67 == 67(68 -1)
        if list2[i +1] == list2[i] -1:

            # add 68 to numbs list
            numbs_list.append(list2[i])

            # remove 68 from list2
            list2.pop(list2.index(list2[i]))
        else:
            list2.pop(list2.index(list2[i]))
    else:
        complete = True

    # start += 1
    # if start == end:
    #     complete = True

# from list2 this is what i need numbs_list to have stored once the while loop is done:
numbs_list = [68, 21, 20, 1]
# whats left in list2 does not matter after the numbs_list is finalised as list2 will eventually get cleared and repopulated.
####################################################

\"next-in-line\" 可能是错误的措辞,但我想你明白我的意思。如果不是这里的一些例子:

1,0
11,10,9
23,22
58,57
91,90,89,88

请注意任何和所有这些数字之间都没有空间?因为他们都是下一个。

    标签: python


    【解决方案1】:

    你让这件事变得比它需要的复杂得多。只要记住最后一个数字是什么,如果新数字在它下面,然后将它添加到您的列表中。

    list2 = [68, 67, 53, 21, 20, 19, 9, 7, 1, 0]
    maybe = []
    last = -99
    curr = []
    for n in list2:
        if n == last-1:
            maybe[-1].append(n)
        else:
            maybe.append( [n] )
        last = n
    numbs_list = [k for k in maybe if len(k) > 1]
    print(numbs_list)
    

    【讨论】:

      【解决方案2】:

      尝试遍历每个索引并将其与索引进行比较 - 1。如果它们仅相隔 1,则将索引附加到额外列表

      list2 = [68, 67, 53, 21, 20, 19, 9, 7, 1, 0]
      
      extra = []
      for i in range(1,len(list2)):
          if list2[i-1] == list2[i] + 1:
              extra.append(list2[i-1])
      
      print(extra)
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-18
        • 1970-01-01
        • 1970-01-01
        • 2018-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-29
        相关资源
        最近更新 更多