我正在尝试创建一个函数,该函数将输入2个字符串(myString和charString)并查看charString中的字母在myString中的次数。然后将这些值附加到列表中。例如(“所有在西部前面都很安静”,“tqe”)应该返回[“t = 4”,“q = 1”,“e = 4”]。这就是我所拥有的:
def myProblem(myString, charString):
myString = str(myString)
charString = str(charString)
count = 0
newList = []
for letter in charString:
if letter in myString:
count += 1
newList.append(str(letter)+"="+str(count))
else:
pass
return newList
答案 0 :(得分:2)
你绝对应该使用str.count
,而且你没有以正确的方式附加列表。由于您需要总数,因此在每次迭代时附加它都会适得其反。
这是一个正确的版本:
def myProblem(myString, charString):
myString = str(myString)
charString = str(charString)
newList = []
for letter in charString:
newList.append(letter +"="+str(myString.count(letter)))
return newList
print(myProblem('all is quiet on the western front', 'tqe'))
<强>输出强>
['t=4', 'q=1', 'e=4']
请注意,如果将两个参数都放在一起并不重要,可以在一行中完成:
def myProblem(myString, charString):
return [letter +"="+str(myString.count(letter)) for letter in charString ]
答案 1 :(得分:0)
这有用吗?
from collections import Counter
def myProblem(myString, charString):
myString = str(myString)
charString = str(charString)
newList = []
for letter in myString:
if letter in charString:
newList.append(str(letter))
else:
pass
newList = dict(Counter(list(newList)))
return newList
a = input("enter the phrase: ")
b = input("enter the letters to look for: ")
print(myProblem(a, b))
它只是将您的输入a拆分为一个列表,只保留b中的字母,然后使用计数器计算它们发生的频率
a = all在西部前方很安静 和b = qte
输出为:{'q':1,'e':4,'t':4}
答案 2 :(得分:0)
根据@ Xander25的建议,您可以使用collections.Counter
from collections import Counter
input_string = "all is quiet on the western front"
char_string = "tqe"
letter_counts = Counter(input_string) # Create a counter object
# output - Counter({' ': 6, 'a': 1, 'e': 4, 'f': 1, 'h': 1, 'i': 2, 'l': 2, 'n': 3, 'o': 2, 'q': 1, 'r': 2, 's': 2, 't': 4, 'u': 1, 'w': 1})
output_counts = {letter: letter_counts[letter] for letter in char_string} # Create dictionary containing counts of letters present in char_string
# output_counts - {'e': 4, 'q': 1, 't': 4}
output_list = [letter + "=" + str(letter_counts[letter]) for letter in char_string]
# output_list - ['t=4', 'q=1', 'e=4']
此外,当您使用collections.Counter时,它不会为字典中不存在的任何键抛出key error
,而是给出值0
。