Python 2.7 将python中的结果转换为字典

Python 2.7 将python中的结果转换为字典,python-2.7,dictionary,Python 2.7,Dictionary,帮助转换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代码结果,其中查找元音在字符串中出现的时间到字典

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}

首先,让我们把
元音
编入字典。我们需要第二个循环来保持在第一个循环中进行的匹配:

s = "apples"
vowels = dict.fromkeys('aeiou', 0)
matches = {}
我们需要稍微修改
for
循环,以增加相应键(元音)的值:

上面的
for
循环检查
char
是否是元音(或者简单地说,是在
元音中找到的键之一)。如果是,我们将相应键的值增加1。例如,如果
char
是“a”,则
if
语句将返回True,并且键(“a”)的值(冒号后的整数)将增加1。现在,我们只需将值大于0的所有键放入
匹配项中
字典:

for vowel in vowels:
    if vowels[vowel] < 1:    # The vowel didn't appear in the word
        continue
    else:
        matches[str(vowel)] = vowels[vowel]
print matches
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)
完整代码:

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
count=0
s=“苹果”
元音=dict.fromkeys('aeiou',0)
匹配项={}
对于s中的字符:
如果元音中有字符:
元音[char]+=1
对于元音中的元音:
如果元音[元音]<1:
持续
其他:
匹配[str(元音)]=元音[元音]
打印匹配

这样一个简单的更改就可以了:不是增加
count+=1
,而是直接在字典上增加:

for vowel in vowels:
    if vowels[vowel] < 1:    # The vowel didn't appear in the word
        continue
    else:
        matches[str(vowel)] = vowels[vowel]
print matches
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)

你想买哪本词典?从一个元音到它出现的次数?你的元音词典可以用
dict.fromkeys('aeiou',0)
更简单地实例化。你的缩进是关闭的,并且在
元音中没有任何内容。\u dict
最初那么你打算如何向一个不存在的键添加任何内容呢?@PythonMaster:注意
else
元音dict[char]=1
else
中的冒号被省略了,但是代码的逻辑是正确的。我现在已经修复了它。现在它更有意义了,很抱歉!