繁体   English   中英

在 Python 中拆分列表和元组

[英]Split lists and tuples in Python

我有一个简单的问题。

我有一个列表或一个元组,我想将它拆分成许多包含相同元素的列表(或元组)。

我将尝试使用示例更清楚:

(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)

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

我能怎么做? 我知道元组和列表没有属性“split”,所以我想我可以把它们变成字符串。 这是我试过的:

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)]

您可以使用 groupby。

import itertools as it

[list(grp) if isinstance(t,list) else tuple(grp) for k, grp in it.groupby(t)]

例子:

>>> t = (1,2,3,3,3,3) 
[(1,), (2,), (3, 3, 3, 3)]

>>> t = [2,2,3,3,2,3]
[[2, 2], [3, 3], [2], [3]]

您也可以尝试使用 for 循环:

def group_lt(list_or_tuple):
    result = []
    for x in list_or_tuple:
        if not result or result[-1][0] != x:
            result.append(type(list_or_tuple)([x]))
        else:
            result[-1] += type(list_or_tuple)([x])
    return result

t = (1,1,2,2,3,3,4)
print(group_lt(t))  # [(1,1),(2,2),(3,3),(4,)]

l = [2,2,3,3,2,3]    
print(group_lt(l))  # [[2,2],[3,3],[2],[3]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM