如何根据python中的条件在列表中组合或保留字符串? [英] how to combine or leave strings in the lists depending on the condition in python?

查看:431
本文介绍了如何根据python中的条件在列表中组合或保留字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个列表:

li1 = ["a", "a", "a", "a", "b", "b", "a", "a", "b"]
li2 = ["a", "a", "a", "b", "a,", "b", "a", "a"]
li3 = ["b", "b", "a", "a", "b"]

我想按"b"

结果应该看起来像这样:

The result is supposed to look like this:

li1 = ["aaaa", "b", "b", "aa", "b"]
li2 = ["aaa", "b", "a", "b", "aa"]
li3 = ["b", "b", "aa", "b"]

但是我不知道该如何处理...请帮助我!

But I don't know how to approach this... please help me!

推荐答案

使用 如果要加入属于某个键的

If you want to join groups not belonging to a certain key

from itertools import groupby

def join_except_key(iterable, key='b'):
    groups = groupby(iterable)
    for k, group in groups:
        if k != key:
            yield ''.join(group) # more general: ''.join(map(str, group))
        else:
            yield from group

演示:

>>> li1 = ["a", "a", "a", "a", "b", "b", "a", "a", "b", "c", "c", "b", "c", "c"]
>>> list(join_except_key(li1))
['aaaa', 'b', 'b', 'aa', 'b', 'cc', 'b', 'cc']

如果要加入属于某个键的组

from itertools import groupby

def join_by_key(iterable, key='a'):
    groups = groupby(iterable)
    for k, group in groups:
        if k == key:
            yield ''.join(group) # more general: ''.join(map(str, group))
        else:
            yield from group

演示:

>>> li1 = ["a", "a", "a", "a", "b", "b", "a", "a", "b", "c", "c", "b", "c", "c"]
>>> list(join_by_key(li1))
['aaaa', 'b', 'b', 'aa', 'b', 'c', 'c', 'b', 'c', 'c']

groupby产生的内容的详细信息(join_except_key的非生成器方法)

Details on what groupby produces (non generator approach for join_except_key)

>>> li1 = ["a", "a", "a", "a", "b", "b", "a", "a", "b", "c", "c", "b", "c", "c"]
>>> groups = [(k, list(group)) for k, group in groupby(li1)]
>>> groups
[('a', ['a', 'a', 'a', 'a']),
 ('b', ['b', 'b']),
 ('a', ['a', 'a']),
 ('b', ['b']),
 ('c', ['c', 'c']),
 ('b', ['b']),
 ('c', ['c', 'c'])]
>>>
>>> result = []
>>> for k, group in groups:
...:    if k != 'b':
...:        result.append(''.join(group))
...:    else:
...:        result.extend(group)
...:
>>> result
['aaaa', 'b', 'b', 'aa', 'b', 'cc', 'b', 'cc']

第二行中的列表理解groups = [...仅用于检查分组操作的元素,仅使用groups = groupby(li1)即可正常工作.

The list comprehension groups = [... in the second line was only needed for inspecting the elements of the grouping operation, it works fine with just groups = groupby(li1).

这篇关于如何根据python中的条件在列表中组合或保留字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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