【问题标题】:Changing letters in string to letter and number of frequency-python [duplicate]将字符串中的字母更改为字母和频率-python的数量[重复]
【发布时间】:2019-04-20 23:12:59
【问题描述】:

我正在寻找解决问题的方法。我想制作一个有人输入字符串的程序,然后我将其覆盖为如下内容:

'ZZZZYYYZZ' -> 'Z4Y3Z2'

我愿意接受任何建议。

我做的代码:

def compress(s):
    e={}
    if s.isalpha():
        for i in s:
            if i in e:
                e[i] += 1
            else:
                e[i] = 1
    else:
        return None    

    return ''.join(['{0}{1}'.format(k,v)for k,v in e.items()])

s=input("Write string: ")
compress(s)

这会产生错误的输出

Write string: ZZZZYYYZZ
Y3Z6

【问题讨论】:

  • 您要实现的目标称为运行长度编码,并且已经有几种解决方案。

标签: python string python-3.x list numbers


【解决方案1】:

将未排序的数据分组为 itertools.groupby 的工作。

>>> from itertools import groupby
>>> 
>>> s = 'ZZZZYYYZZ'
>>> ''.join('{}{}'.format(c, len(list(g))) for c, g in groupby(s))
'Z4Y3Z2'

详细介绍 groupby 在此处生成的内容:

>>> [(c, list(g)) for c, g in groupby(s)]
[('Z', ['Z', 'Z', 'Z', 'Z']), ('Y', ['Y', 'Y', 'Y']), ('Z', ['Z', 'Z'])]

~编辑~

没有中间列表的轻微内存优化:

>>> ''.join('{}{}'.format(c, sum(1 for _ in g)) for c, g in groupby(s))
'Z4Y3Z2'

~编辑2~

我们可以只用 C 代替 C1 吗?

>>> s = 'XYXYXXX'
>>> to_join = []
>>> groups = groupby(s)
>>> 
>>> for char, group in groups:
...:    group_len = sum(1 for _ in  group)
...:    if group_len == 1:
...:        to_join.append(char)
...:    else:
...:        to_join.append('{}{}'.format(char, group_len))
...:        
>>> ''.join(to_join)
'XYXYX3'

【讨论】:

  • 感谢您的快速回复。它有效,非常感谢您的帮助。我找不到它,因为我不确定如何定义我的问题。现在我什么都明白了>u
  • 我一定会这样做的 ^^ 我是新来的,我正在学习一切。我还有一个问题——是否有机会改变一封信的显示?例如,而不是 C1 只有 C?
  • @KimikoSourire 是的,但是通过这个额外的检查,编写传统的for 循环可能更具可读性。
  • 非常感谢 - 我试图做循环,但效果不佳:
【解决方案2】:

这有助于巧妙地使用zip,允许您遍历每个字符和下一个字符:

s = 'ZZZZYYYZZ'
out = ''
count = 1
for a, b in zip(s[:-1], s[1:]):
    print(a, b)
    if a != b:
        out += a + str(count)
        count = 1
    else:
        count += 1

out += s[-1] + str(count)

out 设为'Z4Y3Z2'

【讨论】:

  • 对,我没有那样想。我试图创建比较字符串列表的两个元素的循环,但效果不佳。感谢您的回复
猜你喜欢
  • 2017-04-20
  • 2014-06-19
  • 2021-12-31
  • 1970-01-01
  • 1970-01-01
  • 2017-08-30
  • 2023-03-25
  • 2019-06-04
相关资源
最近更新 更多