我现在有代码尝试让我按任意深度键(如mongo)对字典进行排序,但它要求我对密钥的深度进行硬编码。
#This is the code for inside the function, you need to make a function to receive the arguments
#and the dictionary. the arguments should be listed in order of layers. It then splits the argument string
#at the "." and assigns to each of the items.From there it should return the "l[]".
#you need to set it up to pass the arguments to these appropriate spots. so the list of dicts goes to
#list and the arguments go to argstring and it should be taken care of from there.
#splitting the argument
argstring="author.age"
arglist = argstring.split(".")
x=(5-len(arglist))#need to set this number to be the most you want to accept
while x>0:
arglist.append('')
x-=1
#test list
list = [
{'author' : {'name':'JKRowling','age':47,'bestseller':{'series':'harrypotter','copiessold':12345}}},
{'author' : {'name':'Tolkien','age':81,'bestseller':{'series':'LOTR','copiessold':5678}}},
{'author' : {'name':'GeorgeMartin','age':64,'bestseller':{'series':'Fire&Ice','copiessold':12}}},
{'author' : {'name':'UrsulaLeGuin','age':83,'bestseller':{'series':'EarthSea', 'copiessold':444444}}}
]
l=[]#the list for returning
#determining sort algorythm
l = sorted(list, key=lambda e: e[arglist[0]][arglist[1]])#need add as many of these as necesarry to match the number above
print()
这很有效,但是必须手动指定arglist中的参数似乎很愚蠢。 如果我需要5深,我需要手动指定e 5次.. 有没有办法使用列表推导或for循环自动包含任意元素深度?
答案 0 :(得分:4)
使用reduce()
:
sorted(list, key=lambda e: reduce(lambda m, k: m[k], argslist, e))
reduce()
接受一个函数,一个输入列表和一个可选的初始值,然后将该函数重新应用于next元素和最后一次调用的返回值(从初始值开始)。因此,它运行m[k0][k1][k2]..[kn]
,其中k
的连续argslist
值取自>>> e = {'author' : {'name':'JKRowling','age':47,'bestseller':{'series':'harrypotter','copiessold':12345}}}
>>> argslist = ['author', 'age']
>>> reduce(lambda m, k: m[k], argslist, e)
47
。
简短演示:
{{1}}
答案 1 :(得分:0)
使用for循环来遍历args
没有错>>> e = {'author' : {'name':'JKRowling','age':47,'bestseller':{'series':'harrypotter','copiessold':12345}}}
>>> argslist = ['author', 'age']
>>> result = e
>>> for arg in argslist:
... result = result[arg]
...
>>> result
47
这种方式非常容易调试,你可以放try/except
,print
,断点等。