Combine elements of lists if some condition

后端 未结 3 1738
一生所求
一生所求 2021-01-18 00:06

How do I combine the elements of a list if some condition is met.

I\'ve seen posts about combining elements of a list, but not with some condition.

3条回答
  •  一向
    一向 (楼主)
    2021-01-18 00:54

    Here's my solution:

    words = [
        ['this','that!','riff','raff'],
        ['hip','hop!','flip!','flop'],
        ['humpty','dumpty!','professor!','grumpy!']
    ]
    
    output = []
    for wl in words:
        out_wl = []
        bang_wl = []
        for w in wl:
            if '!' in w:
                bang_wl.append(w)
            else:
                if bang_wl:
                    out_wl.append(','.join(bang_wl))
                    bang_wl = []
                out_wl.append(w)
        if bang_wl:
            out_wl.append(','.join(bang_wl))
        output.append(out_wl)
    
    print output
    

    Output:

    [['this', 'that!', 'riff', 'raff'], ['hip', 'hop!,flip!', 'flop'], ['humpty', 'dumpty!,professor!,grumpy!']]
    

    bang_wl accumulates words with ! until it hits a word that doesn't contain a !. At this point, it joins the words in bang_wl and appends to the output_wl list.

提交回复
热议问题