在列表上查找连续数字的顺序

时间:2019-11-04 20:42:43

标签: python python-3.x list

我有以下形式的列表

[[143], [144, 210, 270], [145]]

具有任意长度的任意数量的子列表。

我想构建一个函数,该函数检查是否有一系列连续的(升序)数字,并选择每个列表的一个元素。序列的第一个元素应该在第一个列表中,第二个元素在第二个列表中,依此类推。如果存在序列,则应返回该序列。不需要找到每个可能的序列。如果序列不存在,则返回'fail'

例如,在上面的示例中,该函数应输出列表[143,144,145]

我写了一个代码,但是它只能部分起作用。代码是

def pattern(example):
    index = [0 for t in example]
    stop = min([len(t) for t in example])
    i=0
    while i < stop:
        attempt = [0 for t in example]
        j = 0
        i+1
        while j < len(example):
            attempt[j] = example[j][index[i]]
            try:
                if example[j+1][index[j+1]] - example[j][index[j]] == 1:
                    j+=1
                    index[j]+=1
                else:
                    break
            except:
                break
        if attempt[-1] != 0:
            return attempt
        else:
            return 'fail'

它仅适用于2个子列表,我不知道为什么。有帮助吗?

5 个答案:

答案 0 :(得分:2)

通过重复查找下一个列表中的下一个in,可以大大简化代码。

def find( list_of_lists ):
    for element in list_of_lists[0]:
        start = element
        next = element
        for list in list_of_lists[1:]:
            next+=1
            print( "looking for {} in {}".format(next, list))
            if not next in list:
                return 'fail'
    return [x for x in range(start,next+1)]

a = [[143], [144, 210, 270], [145]]

find(a)
looking for 144 in [144, 210, 270]
looking for 145 in [145]

[143, 144, 145]

编辑:更正的版本

def find( list_of_lists ):
    num = len(list_of_lists)
    for start in list_of_lists[0]:
        try:
            print( "starting with", start )
            next = start
            last = start + num - 1
            for list in list_of_lists[1:]:
                next+=1
                print( "looking for {} in {}".format(next, list))
                if not next in list:
                    raise KeyError()
                elif next == last:
                    return [x for x in range(start,next+1)]
          except KeyError:
              pass
    return 'fail'

find(a)
starting with 1
looking for 2 in [3, 2, 6]
looking for 3 in [5, 7, 4]
starting with 3
looking for 4 in [3, 2, 6]
starting with 5
looking for 6 in [3, 2, 6]
looking for 7 in [5, 7, 4]

[5, 6, 7]

答案 1 :(得分:2)

您可以使用chain来平整列表。

from itertools import chain


def find_consecutive():
    my_list = [[143], [144, 210, 270], [145]]

    flatten_list = list(chain.from_iterable(my_list))

    for idx, item in enumerate(flatten_list):
        current = item
        preserved_items = [item]

        for _idx, _item in enumerate(flatten_list[idx + 1:]):
            if current + 1 == _item:
                current = _item
                preserved_items.append(_item)

        if len(preserved_item) > 1:
            return preserved_items

    return 'fail'


if __name__ == '__main__':
    print(f"consecutive: {find_consecutive()}")

输出:

consecutive: [143, 144, 145]

答案 2 :(得分:1)

使用itertools.product获取所有子列表的叉积,并测试它们中的任何一个是否为连续序列。

import itertools as it

def pattern(example):
    for l in it.product(*example):
        if is_consecutive(l):
            return l
    return 'fail'

def is_consecutive(l):
    return all(l[i] == l[i+1] - 1 for i in range(len(l)-1))

答案 3 :(得分:1)

我喜欢不使用导入的库作为学习体验而尝试。

我采用了这种方法。首先,我简化了您的初始列表,所以只有一个列表可以处理。

然后,我比较了列表中的项目,看它们之间的差异是否为1。我遇到的问题是,我得到了重复的内容(例如144个),并使用dict函数将其删除了。

x = [[133], [144, 134, 136], [135]]
y = []
z = []

def isOne(itm, lst):
    pos = 0
    for stuff in lst:
        sm = stuff - itm
        if sm == 1:
            return pos
        else:
            pos = pos + 1
    return 0



for itms in x:
    for itms2 in itms:
        y.append(itms2)


for itms in y:
    x = isOne(itms, y)
    if x > 0:
      z.append(itms)
      z.append(y[x])

z = list(dict.fromkeys(z))


print(z)

答案 4 :(得分:0)

您可以使用函数chain()

from itertools import chain

it = chain.from_iterable(lst)
# add the first item from the iterator to the list
result = [next(it)]

for i in it:
    if result[-1] == i - 1:
        result.append(i)