计算单词数组中相同的连续字母 - python

我的目标是计算列表中的重复字母。因此,如果我有一个列表words = ['capps','bat','hatt'],我将获得一个输出[1,0,1]的计数器列表。如果输入是['apple aab','gabb','ppl'] the result should be [2,1,1]

我的策略是获取此列表,将其转换为字符串,然后使用list函数将其分解为各个字母。我可以迭代此数组并计算得到的重复项数量。这是解决此问题的正确方法吗?

words = ['apple','gabb','ppl']
words = " ".join(str(x) for x in words)
result = [character for character in words]
counter = 0
tmp = []
for i in range(len(result)-1):
    if result[i] == result[i+1]:
        if result[i] and result[i+1] != ' ':
            counter+=1
        else:
            tmp.append(0)
    tmp.append(counter)

print(tmp)

我得到的输出是[0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3]

python大神给出的解决方案

重复表示两个连续的字符相同。

您可以使用itertools.groupby将相同的元素分组。

数对

如果要计数连续对的总数,例如'appple'有两个,则使用以下内容。

from itertools import groupby

words = ['apple aab','gabb','ppl']

counter = []

for word in words:
    counter.append(0)
    for _, group in groupby(word):
        counter[-1] += sum(1 for _ in group) - 1

print(counter) # [2, 1, 1]

计数顺序

如果您需要计算序列数而不管其长度如何(例如,'appple'仅具有一个序列),请使用以下方法:

from itertools import groupby

words = ['apppple aab','gabb','ppl']
#          ^----- one long sequence

counter = []

for word in words:
    counter.append(0)
    for _, group in groupby(word):

        # Here we increment only by one for sequence of length 2 or more
        for word in words:
            if sum(1 for _ in group) > 1:
                counter[-1] += 1

print(counter) # [2, 1, 1]

Python:同时在for循环中添加到列表列表 - python

我想用for循环外的0索引值创建一个新列表,然后使用for循环添加到相同的列表。我的玩具示例是:import random data = ['t1', 't2', 't3'] masterlist = [['col1', 'animal1', 'an…

用大写字母拆分字符串,但忽略AAA Python Regex - python

我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…

如何在Matplotlib条形图后面绘制网格线 - python

x = ['01-02', '02-02', '03-02', '04-02', '05-02'] y = [2, 2, 3, 7, 2] fig, ax = plt.subplots(1, 1) ax.bar(range(len(y)), y, width=…

对于DataFrame的每一行,在给定条件的情况下获取第一列的索引到新列中 - python

这是我的数据框的一部分。data = [ ['1245', np.nan, np.nan, 1.0, 1.0, ''], ['1246', np.nan, 1.0, 1.0, 1.0, ''], ['1247', 1.0, 1.0, 1.0, 1.0, �…

在Flask中测试文件上传 - python

我在Flask集成测试中使用Flask-Testing。我有一个表单,该表单具有我要为其编写测试的徽标的文件上传,但是我不断收到错误消息:TypeError: 'str' does not support the buffer interface。我正在使用Python3。我找到的最接近的答案是this,但是它对我不起作用。这是我的许多尝…