[python] 두 알파벳 문자 사이의 대시 수를 계산하는 방법은 무엇입니까?

알파벳 문자와 대시가 있고이 문자열에서 두 알파벳 문자 사이의 대시 수를 계산하려는 경우. 가장 쉬운 방법은 무엇입니까?

예:

입력: a--bc---d-k

산출: 2031

이것은 a와 b 사이에 2 개의 대시, b와 c 사이에 0의 대시, c와 d 사이에 3 개의 대시, d와 k 사이에 1 개의 대시가 있음을 의미합니다.

파이썬 에서이 출력 목록을 찾는 좋은 방법은 무엇입니까?



답변

정규식 솔루션 :

import re

x = 'a--bc---d-k'

results = [
    len(m) for m in
    re.findall('(?<=[a-z])-*(?=[a-z])', x)
]
print(results)
print(''.join(str(r) for r in results))

산출:

[2, 0, 3, 1]
2031

무차별 강제 루프 논리가있는 솔루션 :

x = 'a--bc---d-k'

count = 0
results = []
for c in x:
    if c == '-':
        count += 1
    else:
        results.append(count)
        count = 0
results = results[1:]  # cut off first length
print(results)

산출:

[2, 0, 3, 1]


답변

다음과 같이 매우 간단한 솔루션을 사용할 수 있습니다.

import re

s = 'a--bc---d-k'
# Create a list of dash strings.
dashes = re.split('[a-z]', s)[1:-1]
# Measure the length of each dash string in the list and join as a string.
results = ''.join([str(len(i)) for i in dashes])

산출:

‘2031’


답변

입력이 대시로 시작될 수 있다면 다음을 사용할 수 있습니다.

def count_dashes(string):
    all_counts = []
    dash_count = 0
    for char in string:
        if char == "-":
            dash_count += 1
        else:
            all_counts.append(dash_count)
            dash_count = 0
    return all_counts

그러나 입력이 항상 문자로 시작하면 목록의 맨 앞에있는 0이 마음에 들지 않을 수 있습니다.

int 문자열로 출력이 필요한 경우 다음을 추가 할 수 있습니다.

def count_dashes(string):
    all_counts = []
    dash_count = 0
    for char in string:
        if char == "-":
            dash_count += 1
        else:
            all_counts.append(dash_count)
            dash_count = 0
    return "".join([str(number) for number in all_counts])


답변

간단한 루프 접근 방식은 다음과 같습니다.

myinput = 'a--bc---d-k'
output = []
output_count = -1
for elem in myinput:
  if elem == '-':
    output[output_count] = output[output_count]+1
  else:
    output.append(0)
    output_count += 1

print(output)


답변