第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何識別字典中的匹配值并僅使用這些鍵創(chuàng)建一個新字符串?

如何識別字典中的匹配值并僅使用這些鍵創(chuàng)建一個新字符串?

藍(lán)山帝景 2021-09-28 17:47:55
我有一種方法可以從字符串中提取重復(fù)字母并將它們添加到字典中,并將它們重復(fù)的次數(shù)作為值。現(xiàn)在我想做的是拉出所有具有匹配值的鍵并創(chuàng)建一個僅包含這些鍵的字符串。例子:text = "theerrrdd"count = {}same_value = ""for ch in text:    if text.count(ch) > 1:        count[ch] = text.count(ch)如何檢查具有匹配值的鍵的計數(shù),如果找到,將這些鍵添加到 same_value?因此,在此示例中,“e”和“d”的值都為 2。我想將它們添加到 same_value,以便在調(diào)用時 same_value 將返回“ed”。我基本上只是想能夠識別哪些字母重復(fù)了相同的時間。
查看完整描述

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ù)雜度。


查看完整回答
反對 回復(fù) 2021-09-28
?
青春有我

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


查看完整回答
反對 回復(fù) 2021-09-28
?
Helenr

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)


查看完整回答
反對 回復(fù) 2021-09-28
  • 3 回答
  • 0 關(guān)注
  • 220 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號