2016-11-10 100 views
0

我的老師要求我編寫一個函數來使用另一個字符串字母來計算字符串的出現次數。因此,例如:單獨計算字符串中的多個字符

>>>problem3("all is quiet on the western front", "tqe") 
>>>["t=4", "q=1", "e=4"] 

但是我只能讓它做:

>>>problem3("all is quiet on the western front", "tqe") 
>>>[4, 1, 4] 

這是我的代碼:

def problem3(myString, charString): 
    return [myString.count(x) for x in (charString)] 

我如何得到它以這種形式[「T = 4「,」q = 1「,」e = 4「]?

回答

1

所以,你只是被要求非常明確格式化和你接近,只需要格式化結果:

def problem3(myString, charString): 
    return ['{}={}'.format(x, myString.count(x)) for x in charString] 

>>> problem3("all is quiet on the western front", "tqe") 
['t=4', 'q=1', 'e=4'] 
+0

你是最好的,謝謝。 – thatoneguy