【问题标题】:max with dictionaries python, same structure, different output?最大与字典python,相同的结构,不同的输出?
【发布时间】:2015-10-24 01:58:08
【问题描述】:

第一个结构:

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

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

输出为 6

第二个结构:

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

【问题讨论】:

  • total = [dic[num]] 应该做什么?您只存储一个值,即最后一个 dic[num]

标签: python python-2.7 for-loop dictionary max


【解决方案1】:

您只会将 last 值放入您的 total 列表中:

for key in dic:
    total = [dic[key]]

这会将total 每次重新绑定到一个新列表。这取决于字典的顺序,即dependent on the dictionary insertion and deletion history

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

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

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

print(max(total))

【讨论】:

  • 在第二种情况下,我真的看不出字典值在哪里或为什么是字符串而不是整数?你能帮忙吗?
  • @Jalanji:那是我的错误。
猜你喜欢
  • 2016-08-02
  • 1970-01-01
  • 2013-09-04
  • 2020-02-17
  • 2021-11-15
  • 1970-01-01
  • 2019-08-18
  • 2018-01-29
  • 1970-01-01
相关资源
最近更新 更多