如何计算一行中字符串中字符的频率?

2024-10-02 00:24:44 发布

您现在位置:Python中文网/ 问答频道 /正文

input = 'XXYXYYYXYXXYYY'

输出=[2,1,1,3,1,1,2,3]

如何按输入顺序计算字符串中X和Y的数量,然后将这些值放入列表中


Tags: 字符串列表input数量顺序xxyxyyyxyxxyyy
3条回答

您可以通过迭代整个列表使用while循环来实现这一点

str = 'XXYXYYYXYXXYYY';
i = 0
output = []
k = 1
while i < len(str) - 1:
   if str[i] == str[i+1]:
      k = k + 1
   else:
      output.append(k)
      k = 1
   i = i + 1
output.append(k)
print(output)

输出

[2, 1, 1, 3, 1, 1, 2, 3]
import itertools
numbers = []
input = 'XXYXYYYXYXXYYY'
split_string = [''.join(g) for k, g in itertools.groupby(input)]

for i in split_string:
    numbers.append(len(i))
print(numbers)

输出:

[2, 1, 1, 3, 1, 1, 2, 3]

尝试使用itertools.groupby

from itertools import groupby
s = 'XXYXYYYXYXXYYY'
print([len(list(i)) for _, i in groupby(s)])

相关问题 更多 >

    热门问题