合并列表中的元素(如果有条件) [英] Combine elements of lists if some condition

查看:74
本文介绍了合并列表中的元素(如果有条件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果满足某些条件,如何合并列表 的元素.

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.

说我有一个包含单词列表的列表:

Say I have a list containing lists of words:

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

如何仅合并包含!的那些元素?

How do I combine only those elements that contain an !?

例如,输出将如下所示:

For example, the output would look like this:

[['this', 'that!', 'riff', 'raff'],
 ['hip', 'hop!, flip!', 'flop'],  # 1,2 are now combined
 ['humpty', 'dumpty!, professor!, grumpy!']]   # 1,2,3 are now combined

我尝试过:

for word in words:
    word = ', '.join(i for i in word if re.search('!',str(i)))
    print word

但是得到了

that!
hop!, flip!
dumpty!, professor!, grumpy!

谢谢.

推荐答案

使用 itertools.groupby :

>>> from itertools import groupby
>>> out = []
>>> for lst in words:
    d = []
    for k, g in groupby(lst, lambda x: '!' in x):
        if k:
            d.append(', '.join(g))
        else:
            d.extend(g)
    out.append(d)
...     
>>> out
[['this', 'that!', 'riff', 'raff'],
 ['hip', 'hop!, flip!', 'flop'],
 ['humpty', 'dumpty!, professor!, grumpy!']]

这篇关于合并列表中的元素(如果有条件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆