如何对不同的列表元素进行分组,包括' _'进入列表而不改变顺序顺序?

时间:2017-09-02 11:45:53

标签: python

rawinput:

lst = ['a_app','a_bla','a_cat','b','c','d_d1','d_xe','d_c','e_1','e_2','f']

lst中的元素是字符串

预期结果:

new_lst = [['a_app','a_bla','a_cat'],'b','c',['d_d1','d_xe','d_c'],['e_1','e_2'],'f']

包括'_'在内的任何元素都会被归为一个列表元素,但如果不同,则其开头将分组到不同的列表中,例如['a_app','a_bla','a_cat']['d_d1','d_xe','d_c']

注意:新列表的顺序不会只改变压缩字符串,包括' _'进入清单。

2 个答案:

答案 0 :(得分:5)

您可以使用itertools.groupby

>>> from itertools import groupby
>>> lst = ['a_app','a_bla','a_cat','b','c','d_d1','d_xe','d_c','e_1','e_2','f']
>>> [list(strs) for _,strs in groupby(lst, lambda s: s.split('_')[0])]
[['a_app', 'a_bla', 'a_cat'], ['b'], ['c'], ['d_d1', 'd_xe', 'd_c'], ['e_1', 'e_2'], ['f']]

现在你编写了一些代码,这里有一种将1元素子列表转换为字符串的方法:

>>> new_list = [list(strs) for _,strs in groupby(lst, lambda s: s.split('_')[0])]
>>> [strs if len(strs) > 1 else strs[0] for strs in new_list]
[['a_app', 'a_bla', 'a_cat'], 'b', 'c', ['d_d1', 'd_xe', 'd_c'], ['e_1', 'e_2'], 'f']

但是,使用列表列表可能比使用混合类型(列表和字符串)的列表更容易。

答案 1 :(得分:0)

这可以通过以下代码实现:

lst = ['a_app','a_bla','a_cat','b','c','d_d1','d_xe','d_c','e_1','e_2',f]
new_lst = []
tmp = [] # This will be used to group elements like 'a_app' and 'a_bla'.

for el in lst:
    # If _ is not in string, we add the string directly to new_lst
    # and continue with next string.
    if '_' not in el:
        new_lst.append(el)
        continue

    # If tmp is empty, we just add the current string. It obviously
    # contains _, otherwise we wouldn't get there (above if clause).
    if tmp == []:
        tmp.append(el)
        continue

    # Compare first letter of current string with the first letter of
    # first string in tmp. If it is the same, add current string to tmp.
    if el[0] == tmp[0][0]:
        tmp.append(el)

    # If it is not the same, that means that tmp is ready to be appended
    # new_lst. We must also reset the tmp.
    else:
        new_lst.append(tmp)
        tmp = []
相关问题