3 回答

TA貢獻(xiàn)1802條經(jīng)驗 獲得超5個贊
首先創(chuàng)建一個字母來計數(shù)映射,然后反轉(zhuǎn)這個映射。使用collections模塊:
from collections import defaultdict, Counter
text = 'theerrrdd'
# create dictionary mapping letter to count
letter_count = Counter(text)
# reverse mapping to give count to letters mapping
count_letters = defaultdict(list)
for letter, count in letter_count.items():
count_letters[count].append(letter)
結(jié)果:
print(count_letters)
defaultdict(<class 'list'>, {1: ['t', 'h'],
2: ['e', 'd'],
3: ['r']})
然后,例如,count_letters[2]為您提供在輸入字符串中出現(xiàn)兩次的所有字母。
使用str.count在一個循環(huán)是低效的,因為它需要你的字符串的完全重復(fù)每個字母。換句話說,這樣的算法具有二次復(fù)雜度,而collections.Counter具有線性復(fù)雜度。

TA貢獻(xiàn)1784條經(jīng)驗 獲得超8個贊
另一種方法是使用set()僅獲取字符串中的唯一字符,遍歷集合并創(chuàng)建一個字典,其中計數(shù)是每個計數(shù)的字符列表的鍵。然后,您可以使用 為每個計數(shù)生成字符串join()。
text = "theerrrdd"
chars = set(text)
counts = {}
for ch in chars:
ch_count = text.count(ch)
if counts.get(ch_count, None):
counts[ch_count].append(ch)
else:
counts[ch_count] = [ch]
# print string of chars where count is 2
print(''.join(counts[2]))
# OUTPUT
# ed

TA貢獻(xiàn)1780條經(jīng)驗 獲得超4個贊
我認(rèn)為最簡單的解決方案!
from collections import Counter
text = "theerrrdd"
count = Counter(text)
same_value = ''.join([k for k in count.keys() if count[k] > 1])
print(count)
print(same_value)
添加回答
舉報