【发布时间】:2021-08-14 02:22:35
【问题描述】:
我有以下字典列表:
lines = [
{
"attribute": [
{
"hello": "world"
},
{
"number": "2.2"
},
{
"this": "that"
}
],
"subline": [
{
"attribute": [
{
"number": "1"
}
]
},
{
"attribute": [
{
"number": "0"
}
]
},
{
"attribute": [
{
"number": "5"
}
]
}
]
},
{
"attribute": [
{
"number": "0.2"
}
],
"subline": []
},
{
"attribute": [],
"subline": [
{
"attribute": [
{
"number": "20.2"
}
]
},
{
"attribute": [
{
"number": "1"
},
{
"data": "15"
}
]
}
]
}
]
我想根据字典列表中属性列表中字符串“number”的值对列表进行排序。
此外,根据相同的标准(字典子行列表内的属性编号)对子行列表进行排序。
有时属性“编号”不存在,有时“子行”列表可能为空。
期望的结果是:
lines = [
{
"attribute": [
{
"number": "0.2"
}
],
"subline": []
},
{
"attribute": [
{
"hello": "world"
},
{
"number": "2.2"
},
{
"this": "that"
}
],
"subline": [
{
"attribute": [
{
"number": "0"
}
]
},
{
"attribute": [
{
"number": "1"
}
]
},
{
"attribute": [
{
"number": "5"
}
]
}
]
},
{
"attribute": [],
"subline": [
{
"attribute": [
{
"number": "1"
},
{
"data": "15"
}
]
},
{
"attribute": [
{
"number": "20.2"
}
]
}
]
}
]
编辑:
我是这样解决的:
lines = [{'attribute': [{'hello': 'world'}, {'number': '2.2'}, {'this': 'that'}], 'subline': [{'attribute': [{'number': '1'}]}, {'attribute': [{'number': '0'}]}, {'attribute': [{'number': '5'}]}]}, {'attribute': [{'number': '0.2'}], 'subline': []}, {'attribute': [], 'subline': [{'attribute': [{'number': '20.2'}]}, {'attribute': [{'number': '1'}, {'data': '15'}]}]}]
def getAttributeNumber(lineObject):
try:
if isinstance(lineObject.get("subline", []), list):
if len(lineObject.get("subline", [])) > 0:
lineObject.get("subline", []).sort(key=lambda o: getAttributeNumber(o))
if isinstance(lineObject.get("attribute", []), list):
for attr in lineObject.get("attribute", []):
if isinstance(attr.get("number"), str):
return attr.get("number")
return "A"
except Exception:
return "A"
lines.sort(key=lambda o: getAttributeNumber(o))
实现这一目标的最直接、也许是最快的方法是什么?
【问题讨论】:
-
这能回答你的问题吗? How does the key argument in python's sorted function work? 在您的情况下,
key将是float((x.get("attribute") or [{}])[0].get("number", "inf")) -
"number" 不幸的是,它并不总是列表中的第一个元素,这使得这更具挑战性,您对如何使用 sorted 函数和 lambda 处理有什么建议吗钥匙?
-
编写一个多行函数来查找包含数字的字典。您不必使用 lambda 函数作为键 - 只需一个接收列表元素并返回给出其排序顺序的函数即可。
-
你试过什么?我们如何检查我们提出的方法是否比您已有的方法更快?
-
是的,我已经添加了关于如何解决它的建议,但我不确定这是否是解决这个问题的最快方法。有什么想法吗?
标签: python-3.x list sorting dictionary data-structures