下面的字典僅用于示例目的:
a = [{'name':'sally','age':'31'},{'name':'greg','age':'30'},{'name':'josh','age':'32'},{'name':'bobby','age':'33',]
字典的順序需要遵循年齡。所以我需要檢查字典是否有序,如果年齡不有序,則列印他們的“名字”。
到目前為止我所做的是根據他們的年齡(升序)整理了字典串列
sorted_age = sorted(a, key=lambda d: d['age'])
并比較兩個 dict 以查看它們是否相等。
if a == sorted_age:
continue
else:
print(False)
我需要列印 'sally' 和 'greg',因為他們的年齡不合適。我不知道如何列印他們的名字
uj5u.com熱心網友回復:
您可以使用zip:
[(a, b) for a, b in zip(data, data[1:]) if a['age'] > b['age']]
[({'name': 'sally', 'age': '31'}, {'name': 'greg', 'age': '30'})]
uj5u.com熱心網友回復:
只需遍歷字典:
for da, ds in zip(a, sorted_age):
if da != ds:
print(da['name'])
print('are not in order')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/315999.html
