如何将列表拆分为元组

4
如果我有一个列表。
lst = ['a', 'k', 'b', 'c', 'k', 'd', 'e', 'g']  

我希望您将列表中不含'k'的元素拆分成新列表,并将其转换为元组。因此,我得到了:
(['a'],['b', 'c'], ['d', 'e', 'g'])

我考虑先使用for循环将它们分成不同的列表。

new_lst = []
for element in lst:
    if element != 'k':
        new_ist.append(element)

这个代码可以删除所有的 'k',但是它们都在一起。我不知道如何将它们分成不同的列表。如果要将列表转换为元组,需要在列表内部创建一个列表。

a = [['a'],['b', 'c'], ['d', 'e', 'g']]
tuple(a) == (['a'], ['b', 'c'], ['d', 'e', 'g'])
True

因此,问题是如何将列表拆分为带有子列表的列表。
7个回答

6

你很接近了。你可以将内容追加到另一个名为sublist的列表中,如果找到一个k,则将sublist追加到new_list中:

lst = ['a', 'k', 'b', 'c', 'k', 'd', 'e', 'g']

new_lst = []
sublist = []
for element in lst:
    if element != 'k':
        sublist.append(element)
    else:
        new_lst.append(sublist)
        sublist = []

if sublist: # add the last sublist
    new_lst.append(sublist)

result = tuple(new_lst) 
print(result)
# (['a'], ['b', 'c'], ['d', 'e', 'g'])

如果你感到有冒险精神,你也可以使用groupby。其思路是按照“k”或“非k”分组,并在该属性上使用groupby

from itertools import groupby

lst = ['a', 'k', 'b', 'c', 'k', 'd', 'e', 'g']
result = tuple(list(gp) for is_k, gp in groupby(lst, "k".__eq__) if not is_k)

print(result)
# (['a'], ['b', 'c'], ['d', 'e', 'g'])

感谢@YakymPirozhenko提供了更简单的生成器表达式


3
tuple(list(i) for i in ''.join(lst).split('k'))

输出:

(['a'], ['b', 'c'], ['d', 'e', 'g'])

1
smallerlist = [l.split(',') for l in ','.join(lst).split('k')]
print(smallerlist)

输出

[['a', ''], ['', 'b', 'c', ''], ['', 'd', 'e', 'g']]

然后您可以检查每个子列表是否包含''

smallerlist = [' '.join(l).split() for l in smallerlist]
print(smallerlist)

输出

[['a'], ['b', 'c'], ['d', 'e', 'g']]  

1
这里有一种不同的方法,使用re模块中的re.splitmap函数:
import re

lst = ['a', 'k', 'b', 'c', 'k', 'd', 'e', 'g']

tuple(map(list, re.split('k',''.join(lst))))

(['a'], ['b', 'c'], ['d', 'e', 'g'])

0

使用itertools的另一种方法

import more_itertools

lst = ['a', 'k', 'b', 'c', 'k', 'd', 'e', 'g']

print(tuple(more_itertools.split_at(lst, lambda x: x == 'k')))

提供

(['a'], ['b', 'c'], ['d', 'e', 'g'])

0

如何进行切片操作,而不涉及添加和连接。

def isplit_list(lst, v):
    while True:
        try:
            end = lst.index(v)
        except ValueError:
            break

        yield lst[:end]
        lst = lst[end+1:]

    if len(lst):
        yield lst


lst = ['a', 'k', 'b', 'c', 'k', 'd', 'e', 'g', 'k']

results = tuple(isplit_list(lst, 'k'))

0

试试这个,它可以工作而且不需要任何导入!

>>> l = ['a', 'k', 'b', 'c', 'k', 'd', 'e', 'g']
>>> t = []
>>> for s in ''.join(l).split('k'):
...     t.append(list(s))
...
>>> t
[['a'], ['b', 'c'], ['d', 'e', 'g']]
>>> t = tuple(t)
>>> t
(['a'], ['b', 'c'], ['d', 'e', 'g'])

为什么不编写一个方法,该方法将以列表作为参数,并返回一个元组,如下所示。
>>> def list_to_tuple(l):
...     t = []
...     for s in l:
...             t.append(list(s))
...     return tuple(t)
...
>>> l = ['a', 'k', 'b', 'c', 'k', 'd', 'e', 'g']
>>> l = ''.join(l).split('k')
>>> l = list_to_tuple(l)
>>> l
(['a'], ['b', 'c'], ['d', 'e', 'g'])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接