相关疑难解决方法(0)

python返回列表中连续整数的列表

我有一个整数列表,我想生成一个包含所有连续整数列表的列表.

#I have:
full_list = [0,1,2,3,10,11,12,59]
#I want:
continuous_integers = [[0,1,2,3], [10,11,12], [59]]
Run Code Online (Sandbox Code Playgroud)

我有以下工作,但似乎是一个糟糕的方式:

sub_list = []
continuous_list = []
for x in full_list:
    if sub_list == []:
        sub_list.append(x)
    elif x-1 in sub_list:
        sub_list.append(x)
    else:
        continuous_list.append(sub_list)
        sub_list = [x]
continuous_list.append(sub_list)
Run Code Online (Sandbox Code Playgroud)

我已经看到其他问题表明itertools.groupby是一种有效的方法,但是我不熟悉这个函数,我似乎在编写lambda函数来描述连续性时遇到了麻烦.

问题:有没有更好的方法(可能使用itertools.groupby?)

注意事项:full_list将包含1到59个整数,将始终排序,整数将介于0到59之间.

python lambda group-by continuous python-itertools

5
推荐指数
1
解决办法
552
查看次数

加入元组列表

我的代码看起来如下:

from itertools import groupby

for key, group in groupby(warnstufe2, lambda x: x[0]):

    for element in group:
        a = element[1:4]
        b = element[4:12]
        c = [a,b]
        print(c)
Run Code Online (Sandbox Code Playgroud)

当我打印(c)我得到这样的东西:

[(a,b,c),(d,e,f)] 
[(g,h,i),(j,k,l)]
Run Code Online (Sandbox Code Playgroud)

其中a1 =(a,b,c),b1 =(d,e,f),a2 =(g,h,i),b2 =(j,k,l).当然有a3 ...和b3 ...但是,我需要这样的东西:

[(a,b,c),(d,e,f),(g,h,i),(j,k,l)]
Run Code Online (Sandbox Code Playgroud)

我已经通过c尝试了for循环:

for item in c:
    list1 = []
    data = list1.append(item)
Run Code Online (Sandbox Code Playgroud)

但这没有帮助,导致:

None
None
Run Code Online (Sandbox Code Playgroud)

基于以下链接:https: //mail.python.org/pipermail/tutor/2008-February/060321.html

我似乎很容易,但我是python的新手,并没有找到解决方案,尽管有很多阅读.我感谢您的帮助!

python tuples nested-lists

0
推荐指数
1
解决办法
742
查看次数