繁体   English   中英

Python 的行程编码 Output

[英]Run-Length Encoding Output for Python

这些是我需要执行行程编码分配的规则:

  1. 独立角色将保持不变。 例如“a”→[“a”]。
  2. 一个字符的运行,c,重复N次将被压缩为[“c”,“c”,N]。 例如 "bbbb" → ['b', 'b', 4]。

这就是我的目标 output 看起来像 "aaaabbcccd" → ['a', 'a', 4, 'b', 'b', 2, 'c', 'c', 3, 'd']我希望它工作的方式。 但是,这是来自“abcd”→ ['a', 'a', 1, 'b', 'b', 1, 'c', 'c', 1, d] 的 output 我正在寻找像这样的 output "abcd" → ['a', 'b', 'c', 'd']

string = "aaaabbcccd"

def encode(string):
    counter = 1
    result = ""
    previousLetter = string[0]
    if len(string)==1:
      return string[0]

    for i in range(1,len(string),1):
        if not string[i] == previousLetter:
            result += string[i-1] + string[i-1] + str(counter) 
            previousLetter = string[i]
            counter = 1
        else:
            counter += 1

        if i == len(string)-1:
                result += string[i]

    return result

result = encode(string)
print(result)

我知道这与这一行有关: result += string[i-1] + string[i-1] + str(counter) 所以我正在考虑为字符出现的次数提供某些条件,但它组合到代码中时不再起作用。 也许我可以在第一个代码中更改一些内容来解决问题,而无需执行此额外代码部分,但我目前不知道?

if str(counter) == 1:
    result += string[i]
if str(counter) == 2:    
    result += string[i] + string[i] 
else:
    result += string[i] + string[i] + str(counter)

这应该做你想要的:

def encode(string):
    string_len = len(string)
    i = 0
    result = []
    while i < string_len:
        count = 1
        c = string[i]
        i += 1
        while i < string_len and string[i] == c:
            count += 1
            i += 1
        if count == 1:
            result.append(c)
        else:
            result += [c, c, count]
    return result

它计算每个新字符的运行长度,然后根据长度是 1 还是大于 1,将适当的条目添加到结果列表中。

如果你有 Python3.8,你可以通过walrus operator用一行来完成:

Python 3.8.1 (default, Jan  8 2020, 14:26:07)
[GCC 7.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from itertools import groupby, chain
>>> string = "aaaabbcccd"
>>> encoded = [*chain(*[[k, k, length] if (length := len([*g])) > 1 else [k] for k, g in groupby(string)])]
>>> print(encoded)
['a', 'a', 4, 'b', 'b', 2, 'c', 'c', 3, 'd']

您可以使用 zip 将字符串偏移 1,从而使循环更简单。

st = "aaaabbcccd"

li = []
i=0
for c1,c2 in zip(st,st[1:]):
    i+=1
    if c1 != c2:
        li += [c1,c1,i]
        i=0

li += [c2]   
print(li)

Output:

['a', 'a', 4, 'b', 'b', 2, 'c', 'c', 3, 'd']   

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM