无法在空闲的python 2.7.14上运行函数调用表达式。下面的代码可能有什么问题?
fruit = ['apple', 'orange', 'grape', 'apple',
'orange', 'grape', 'kiwi'] # init the array
#reports the frequency of every item in a list
def analyze_list(l):
counts = {}
for item in l:
if item in counts:
counts[item] = counts[item] + 1
else:
counts[item] = 1
return counts
#let analyze a list
counts = analyze_list(fruit)
print counts
答案 0 :(得分:1)
您的代码没有正确缩进,与if语句对应的else或elif语句必须位于同一个缩进块上。
fruit = ['apple', 'orange', 'grape', 'apple', 'orange', 'grape', 'kiwi'] # init the array
#reports the frequency of every item in a list
def analyze_list(l):
counts = {}
for item in l:
if item in counts:
counts[item] = counts[item] + 1
else:
counts[item] = 1
return counts
#let analyze a list
counts = analyze_list(fruit)
print counts
注意if语句是如何使用else语句的。