我正在写一个字谜程序。用户输入他们想要的单词的长度,例如11然后我的程序将排序的单词存储在dict键中,而值是存储在我的样本输出中的字谜。我只打印具有大多数单词的最大值的值,例如在样本输出中它的3个单词。但如果还有另外一个含有3个单词的值,我希望也可以打印出来。
示例输出:仅打印:
['activations', 'cavitations', 'vacationist']
但我也想要:
['paternoster', 'penetrators', 'transportee']
代码
def main():
wordList = readMatrix()
sortDict = (lengthWord(wordList))
maxSet = max(sortDict.values(), key = len)
print(sorted(maxSet))
for wor in sortDict.values():
if len(maxSet) == len(sortDict.values()):
print(sortDict.values())
def readMatrix():
wordList = []
strFile = open("wordsEn.txt", "r")
lines = strFile.readlines()
for line in lines:
word = line.rstrip().lower()
wordList.append(word)
return tuple(wordList)
def lengthWord(wordList):
lenWord = 11
sortDict = {}
wordList = readMatrix()
for word in wordList:
if len(word) == lenWord:
sortWord = ''.join(sorted(word))
if sortWord not in sortDict:
sortDict[sortWord] = set()
sortDict[sortWord].add(word)
return sortDict
main()
答案 0 :(得分:1)
这个怎么样?
d1 = dict()
d1[0] = 5
d1[1] = 9
d1[2] = 9
d1[3] = 4
maxValue = max(d1.values()) # figure out the max value
print( [key for key in d1 if d1[key]==maxValue] ) # for keys
print( [d1[key] for key in d1 if d1[key]==maxValue] ) # for values
使用Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:16:31) [MSC v.1600 64 bit (AMD64)] on win32
输出:
>>> d1 = dict()
>>> d1[0] = 5
>>> d1[1] = 9
>>> d1[2] = 9
>>> d1[3] = 4
>>> maxValue = max(d1.values()) # figure out the max value
>>> print( [key for key in d1 if d1[key]==maxValue] ) # for keys
[1, 2]
>>> print( [d1[key] for key in d1 if d1[key]==maxValue] ) # for values
[9, 9]
答案 1 :(得分:0)
max
返回最大值,而不是项目。您可以通过执行max(d.values())
找出最大值,并对每个键执行线性搜索,以查看它是否等于最大值。
答案 2 :(得分:0)
如果我理解你,我会做类似的事情:
m = max(sortDict.values())
print [v for v in sortDict.values() if len(v) == m]
或更明确的方式
m = max(sortDict.values())
for val in sortDict.values():
if len(val) == m:
print val