max与字典python,相同的结构,不同的输出?

max与字典python,相同的结构,不同的输出?,python,python-2.7,for-loop,dictionary,max,Python,Python 2.7,For Loop,Dictionary,Max,第一个结构: dic = {'l':2, 'o':3, 'p':6} for key in dic: total = [dic[key]] print max(total) dic = {} print 'Enter line of text' line = input('') words = line.split() print 'Words', words print 'Counting' for word in words: dic[word] = dic.get(wo

第一个结构:

dic = {'l':2, 'o':3, 'p':6}

for key in dic:
    total = [dic[key]]
print max(total)
dic = {}
print 'Enter line of text'
line = input('')
words = line.split()
print 'Words', words
print 'Counting'
for word in words:
    dic[word] = dic.get(word,0) + 1
print 'Dictionary of your text', dic

for num in dic:
    total = [dic[num]]
print max(total)
输出为6

第二种结构:

dic = {'l':2, 'o':3, 'p':6}

for key in dic:
    total = [dic[key]]
print max(total)
dic = {}
print 'Enter line of text'
line = input('')
words = line.split()
print 'Words', words
print 'Counting'
for word in words:
    dic[word] = dic.get(word,0) + 1
print 'Dictionary of your text', dic

for num in dic:
    total = [dic[num]]
print max(total)

输出为1,大部分为1

您仅将最后一个值放入
总计
列表中:

for key in dic:
    total = [dic[key]]
每次都会将
total
重新绑定到一个新列表。这取决于字典的顺序,即

如果您想知道最大值,只需使用
max(dic.values())

如果必须使用循环,则至少将该值附加到现有列表中:

total = []
for key in dic:
    total.append(dic[key])

print(max(total))

total=[dic[num]
应该做什么?您只存储一个值,即最后一个
dic[num]
在第二种情况下,我真的看不出字典值是字符串而不是整数的位置或原因?你能帮忙吗?@Jalanji:那是我的错误。