2017-09-02 63 views
0

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

注意:新列表的順序不會僅將包含'_'的壓縮字符串更改爲列表。

+0

你可以編寫一個函數來用編程語言python來做到這一點。你嘗試過嗎?如果是這樣,請將您的代碼添加到問題中。 –

+0

先顯示你所嘗試過的? – Kallz

回答

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

使用列表列表比使用mixe的列表更容易處理但是類型(列表和字符串)。

+2

謝謝,我會這樣做根據您的提示:lst ='['a_app','a_bla','a_cat','b','c','d_d1','d_xe','d_c',' e_1','e_2','f'] imp = [list(strs)for _,stby in groupby(lst,lambda s:s.split('_')[0])] new_lst = [ ] for imp in: if len(i)== 1: new_lst.append(''。join(i)) else: new_lst.append(i) – Jack

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 = [] 
相關問題