[英]List of dictionaries, comparing 3 of 4 dictionary values
我有一个可行的解决方案,但我想知道是否有更优雅或更“pythonic”的解决方案。 我有一个字典列表。 每个字典都有 4 个键。 我需要检查一个字典的 3 个键的值是否与下一个字典的键值相同。 下面标有“#This code”的代码就是有问题的代码。 有没有更优雅或更紧凑的方法来做到这一点?
我对 Python 相当陌生,这是我在这里的第一篇文章。 谢谢你。
from operator import itemgetter
from pprint import pprint
lst = [{ "fname" : "John", "lname" : "Doe", "age" : 20, "amount":200 },
{ "fname" : "Sue" , "lname" : "Jones", "age" : 17, "amount":800 },
{ "fname" : "Rick", "lname" : "West" , "age" : 25, "amount":280 },
{ "fname" : "Sue" , "lname" : "Jones", "age" : 17, "amount":120 },
{ "fname" : "John", "lname" : "Doe" , "age" : 20, "amount":100 }]
#Sort list
lst_sorted = sorted(lst, key=itemgetter('fname', 'lname', 'age'))
pprint(lst_sorted)
for i in range(0, len(lst_sorted)-1):
print(lst_sorted[i])
print(lst_sorted[i+1])
#This code
if ( lst_sorted[i]['fname'] == lst_sorted[i+1]['fname'] ) and \
( lst_sorted[i]['lname'] == lst_sorted[i+1]['lname'] ) and \
( lst_sorted[i]['age'] == lst_sorted[i+1]['age'] ):
#/This code/
print('equal')
else:
print('not equal')
首先,如果您只是比较排序列表中的顺序项目,则可以在两个切片上使用zip
:
for a, b in zip(lst_sorted[:-1], lst_sorted[1:]):
# do things
zip
运算符将在任意数量的可迭代对象中生成相应元素的元组。
[:-1] 切片将抓取除最后一个元素之外的所有内容,而 [1:] 切片将抓取除第一个元素之外的所有内容,有效地将它们偏移一个。 您可以在此处阅读有关切片的信息。
然后,为了进行比较,您可以使用all
运算符来短路键上的检查,如果失败,则不会进行整个比较。 all(condition_1, ..., condition_n)
等价于condition_1 and ... and condition_n
:
for a, b in zip(lst_sorted[:-1], lst_sorted[1:]):
print(a, b)
#This code
if all(a.get(k) == b.get(k) for k in ['fname', 'lname', 'age']):
#/This code/
print('equal')
else:
print('not equal')
dict.get
将阻止您在缺少KeyError
的情况下出现的情况
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.