计算连续的字符

vas*_*s85 15 python

EDITED 如何计算Python中的连续字符,以查看每个唯一数字在下一个唯一数字之前重复的次数?我对这种语言很陌生,所以我正在寻找一些简单的东西.

起初我以为我可以这样做:

word = '1000'

counter=0
print range(len(word))


for i in range(len(word)-1):
    while word[i]==word[i+1]:
        counter +=1
        print counter*"0"
    else:
        counter=1
        print counter*"1"
Run Code Online (Sandbox Code Playgroud)

因此,通过这种方式,我可以看到每个唯一数字重复的次数.但是当i达到最后一个值时,这当然会超出范围.

在上面的例子中,我希望Python告诉我1重复1,并且0重复3次.但是,由于我的while语句,上面的代码失败了.

我知道你可以通过内置函数来做到这一点,并且更喜欢这种解决方案.有人有任何见解吗?

Ada*_*ith 44

连续计数:

哦没人发布itertools.groupby了!

s = "111000222334455555"

from itertools import groupby

groups = groupby(s)
result = [(label, sum(1 for _ in group)) for label, group in groups]
Run Code Online (Sandbox Code Playgroud)

之后,result看起来像:

[("1": 3), ("0", 3), ("2", 3), ("3", 2), ("4", 2), ("5", 5)]
Run Code Online (Sandbox Code Playgroud)

您可以使用以下内容进行格式化:

", ".join("{}x{}".format(label, count) for label, count in result)
# "1x3, 0x3, 2x3, 3x2, 4x2, 5x5"
Run Code Online (Sandbox Code Playgroud)

总数:

有人在评论关注的是,你想要一个人数的数量,使得"11100111" -> {"1":6, "0":2}.在这种情况下,你想使用collections.Counter:

from collections import Counter

s = "11100111"
result = Counter(s)
# {"1":6, "0":2}
Run Code Online (Sandbox Code Playgroud)

你的方法:

正如许多人所指出的那样,你的方法失败了,因为你是在循环range(len(s))但是解决s[i+1].当i指向最后一个索引时s,这会导致一个一个错误,因此i+1会引发一个错误IndexError.解决这个问题的一种方法是循环range(len(s)-1),但生成迭代的东西更加pythonic.

对于不是绝对巨大的字符串,不是zip(s, s[1:])性能问题,所以你可以这样做:

counts = []
count = 1
for a, b in zip(s, s[1:]):
    if a==b:
        count += 1
    else:
        counts.append((a, count))
        count = 1
Run Code Online (Sandbox Code Playgroud)

唯一的问题是如果它是唯一的,你必须特殊情况下最后一个字符.这可以修复itertools.zip_longest

import itertools

counts = []
count = 1
for a, b in itertools.zip_longest(s, s[1:], fillvalue=None):
    if a==b:
        count += 1
    else:
        counts.append((a, count))
        count = 1
Run Code Online (Sandbox Code Playgroud)

如果你确实有一个真正巨大的字符串,并且无法忍受在内存中同时保存其中两个字符串,则可以使用该itertools配方pairwise.

def pairwise(iterable):
    """iterates pairwise without holding an extra copy of iterable in memory"""
    a, b = itertools.tee(iterable)
    next(b, None)
    return itertools.zip_longest(a, b, fillvalue=None)

counts = []
count = 1
for a, b in pairwise(s):
    ...
Run Code Online (Sandbox Code Playgroud)


B. *_* M. 11

"那种方式"的解决方案,只有基本的陈述:

word="100011010" #word = "1"
count=1
length=""
if len(word)>1:
    for i in range(1,len(word)):
       if word[i-1]==word[i]:
          count+=1
       else :
           length += word[i-1]+" repeats "+str(count)+", "
           count=1
    length += ("and "+word[i]+" repeats "+str(count))
else:
    i=0
    length += ("and "+word[i]+" repeats "+str(count))
print (length)
Run Code Online (Sandbox Code Playgroud)

else:i = 0 length + =("and"+ word [i] +"重复"+ str(count))print(length)

显示:

'1 repeats 1, 0 repeats 3, 1 repeats 2, 0 repeats 1, 1 repeats 1, and 0 repeats 1'
#'1 repeats 1'
Run Code Online (Sandbox Code Playgroud)

#'1重复1'