在Python中拆分列表和元组 [英] Split lists and tuples in Python

查看:1561
本文介绍了在Python中拆分列表和元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的问题.

我有列表或元组,我想将其拆分为包含相同元素的许多列表(或元组).

I have list, or a tuple, and I want to split it into many lists (or tuples) that contain the same elements.

我将通过一个例子来使自己更加清楚:

I'll try to be more clear using an example:

(1,1,2,2,3,3,4)->(1,1),(2,2),(3,3),(4,)

(1,1,2,2,3,3,4) --> (1,1),(2,2),(3,3),(4,)

(1,2,3,3,3,3)->(1,),(2,),(3,3,3,3)

(1,2,3,3,3,3) --> (1,),(2,),(3,3,3,3)

[2,2,3,3,2,3]-> [2,2],[3,3],[2],[3]

[2,2,3,3,2,3] --> [2,2],[3,3],[2],[3]

我该怎么办?我知道元组和列表不具有"split"属性,因此我认为我可以将它们转换成字符串.这就是我尝试过的:

How can I do? I know that tuples and lists do not have the attribute "split" so i thought that i could turn them into strings before. This is what i tried:

def splitt(l)
    x=str(l)
    for i in range (len(x)-1):
        if x[i]!=x[i+1]:
            x.split()
    return x

推荐答案

尝试一下

from itertools import groupby

input_list = [1, 1, 2, 4, 6, 6, 7]
output = [list(g) for k, g in groupby(input_list)]

这篇关于在Python中拆分列表和元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆