按递增顺序按列表列表对字典进行排序

时间:2014-01-30 02:55:06

标签: python list dictionary

我正在尝试按列表列表对字典进行排序。列表列表中的项目 是字典中的键。

类似的东西:

sort_by_increasing_order(['d', 'e', 'f'], {'d': [0, 1], 'e': [1, 2, 3], 'f': [4]})
result: ['f', 'e', 'd']

我的输入列表是:

[
['why', 'was', 'cinderella', 'late', 'for', 'the', 'ball', 'she', 'forgot', 'to', 'swing', 'the', 'bat'],
['why', 'is', 'the', 'little', 'duck', 'always', 'so', 'sad', 'because', 'he', 'always', 'sees', 'a', 'bill', 'in', 'front', 'of', 'his', 'face'],
['what', 'has', 'four', 'legs', 'and', 'goes', 'booo', 'a', 'cow', 'with', 'a', 'cold'], 
['what', 'is', 'a', 'caterpillar', 'afraid', 'of', 'a', 'dogerpillar'],
['what', 'did', 'the', 'crop', 'say', 'to', 'the', 'farmer', 'why', 'are', 'you', 'always', 'picking', 'on', 'me']
]

我的词典有点像这样:

{'to': [7, 11, 17, 23, 24, 25, 26, 33, 34, 37, 39, 41, 47, 48, 53, 56], 
'jam': [20], 'black': [5], 'farmer': [11],
'woodchuck': [54], 'has': [14, 16, 51], 'who': [16]
}

我的目标是

def sort_by_increasing_order(mylist, myDict):
        #temp = sorted(myDict, key=myDict.get)
        temp = sorted(myDict, key=lambda tempKey: for tempKey in mylist, reverse=True )
        return temp

输出将如下所示:

    sort_by_increasing_order(mylist, myDict)
    >> ['to','woodchuck','has','jam','who','farmer','black']

当我尝试按列表排序时,注释行只是按字典键排序。 我的方法不正确。结果应该是具有增加的长度顺序的列表 如上所述的指数。任何想法

3 个答案:

答案 0 :(得分:2)

看起来您正在尝试按字典中列表的长度排序。这就是你要这样做的方式:

def sort_by_increasing_order(l, d):
    return sorted(l, key=lambda i: len(d[i]))

但我建议您使用更清晰的命名方案。

答案 1 :(得分:1)

我只是用你的输入列表来实现它......

source = [
['why', 'was', 'cinderella', 'late', 'for', 'the', 'ball', 'she', 'forgot', 'to', 'swing', 'the', 'bat'],
['why', 'is', 'the', 'little', 'duck', 'always', 'so', 'sad', 'because', 'he', 'always', 'sees', 'a', 'bill', 'in', 'front', 'of', 'his', 'face'],
['what', 'has', 'four', 'legs', 'and', 'goes', 'booo', 'a', 'cow', 'with', 'a', 'cold'], 
['what', 'is', 'a', 'caterpillar', 'afraid', 'of', 'a', 'dogerpillar'],
['what', 'did', 'the', 'crop', 'say', 'to', 'the', 'farmer', 'why', 'are', 'you', 'always', 'picking', 'on', 'me']
]

# words you want to order in order of their number ov appearances
words = ['to','woodchuck','has','jam','who','farmer']

sorted(words, key = lambda word: sum(1 for lst in source if word in lst), reverse=True)

Out[38]: ['to', 'has', 'farmer', 'woodchuck', 'jam', 'who']

答案 2 :(得分:0)

在您的代码列表理解语法错误中,试试这个,

def sort_by_increasing_order(mylist, myDict):
        temp = sorted(myDict, key=lambda tempKey: [tempKey for tempKey in mylist], reverse=True )
        return temp