帮助转换python代码结果,其中发现元音字符串出现在字典中的时间数?将python转换成字典
count = 0
s = "apple"
vowels = ['a' , 'e' , 'i' ,'o' , 'u']
for char in s:
if char in vowels:
count += 1
print ('Number of vowels: ' + str(count))
结果应该是: 苹果:{ 'A':1, 'E':1}
帮助转换python代码结果,其中发现元音字符串出现在字典中的时间数?将python转换成字典
count = 0
s = "apple"
vowels = ['a' , 'e' , 'i' ,'o' , 'u']
for char in s:
if char in vowels:
count += 1
print ('Number of vowels: ' + str(count))
结果应该是: 苹果:{ 'A':1, 'E':1}
像这样的简单的变化会做的:不是递增count += 1
,直接增加在词典:
count = 0
s = "apple"
vowels = ['a' , 'e' , 'i' ,'o' , 'u']
vowels_dict = {}
for char in s:
if char in vowels:
if char in vowels_dict:
vowels_dict[char] +=1
else:
vowels_dict[char] = 1
print (vowels_dict)
你的缩进是关闭的,原来在'vowels_dict'里面什么也没有,所以你如何添加任何东西到一个不存在的键? –
@PythonMaster:注意'else'有'vowels_dict [char] = 1'。 'else'中的冒号被遗漏了,但是代码的逻辑是正确的。我现在修复了它。 – zondo
现在它变得更有意义,对此感到抱歉! –
首先,让我们vowels
到字典中。我们需要的第二个举行对我们做的第一循环的比赛:
s = "apples"
vowels = dict.fromkeys('aeiou', 0)
matches = {}
我们需要稍微修改for
循环递增值对应关键的(元音):
for char in s:
if char in vowels:
vowels[char] += 1
的for
循环上述检查是否char
是元音(或者简单地说,是)在vowels
发现的关键之一。如果是,则我们将相应键的值增加1.例如,如果char
为“a”,则if
语句将返回True,并且键(“a”)的值(冒号后的整数)将增加一。现在,我们需要的是把它的值是在0所有键进入matches
词典:
for vowel in vowels:
if vowels[vowel] < 1: # The vowel didn't appear in the word
continue
else:
matches[str(vowel)] = vowels[vowel]
,最后一行创建了matches
字典(该matches[str(vowel)]
部分)一个新的密钥,然后分配新的价值键等于vowels
字典(= vowels[vowel]
部分)中相应键的值。现在我们需要做的就是打印出来的matches
词典:
print matches
全码:
count = 0
s = "apple"
vowels = dict.fromkeys('aeiou', 0)
matches = {}
for char in s:
if char in vowels:
vowels[char] += 1
for vowel in vowels:
if vowels[vowel] < 1:
continue
else:
matches[str(vowel)] = vowels[vowel]
print matches
你的元音词典可以通过'dict.fromkeys('aeiou',0)'' – zondo
更简单地实例化。这是行得通的,节省了时间打字,谢谢! –
你想要什么词典?从元音到它出现的次数? – Mureinik