python比较两个列表之间的差异
我有两个类似的列表:python比较两个列表之间的差异,python,list,compare,Python,List,Compare,我有两个类似的列表: newList = ( (1546, 'John'), (8794, 'Michael'), (892416, 'Dave'), (456789, 'Lucy'), ) oldList = ( (1546, 'John'), (8794, 'Michael'), (892416, 'Dave'), (246456, 'Alexander') ) def compare(new, old):
newList = (
(1546, 'John'),
(8794, 'Michael'),
(892416, 'Dave'),
(456789, 'Lucy'),
)
oldList = (
(1546, 'John'),
(8794, 'Michael'),
(892416, 'Dave'),
(246456, 'Alexander')
)
def compare(new, old):
print('Alexander is not anymore in the new list !')
print('Lucy is new !')
return newList
我想有一个比较两个列表的函数。应该是这样的:
newList = (
(1546, 'John'),
(8794, 'Michael'),
(892416, 'Dave'),
(456789, 'Lucy'),
)
oldList = (
(1546, 'John'),
(8794, 'Michael'),
(892416, 'Dave'),
(246456, 'Alexander')
)
def compare(new, old):
print('Alexander is not anymore in the new list !')
print('Lucy is new !')
return newList
我想和每个人的id进行比较,这是独一无二的
编辑:结果将是我的函数比较。它显示了差异。
我不知道如何启动您可以使用set:
这是一种比较整个元素id、名称的方法,因此,如果您只想比较id,您应该进行一些修改,例如使用dicts。您可以使用set:
这是一种比较整个元素id、名称的方法,因此,如果您只想比较id,您应该做一些修改,例如使用dicts。您可以将列表转换为集合,并获取差异
n = set(l[1] for l in newList)
o = set(l[1] for l in oldList)
print n - o # set(['Lucy'])
print o - n # set(['Alexander'])
您可以将列表转换为集合并获取差异
n = set(l[1] for l in newList)
o = set(l[1] for l in oldList)
print n - o # set(['Lucy'])
print o - n # set(['Alexander'])
编辑:在我对集合了解很多之前,我就写了这篇文章。现在我推荐使用下面给出的集合的解决方案 一个解决方案:
removed = [o for o in old if o[0] not in [n[0] for n in new]]
added = [n for n in new if n[0] not in [o[0] for o in old]]
或者,如果您将数据显示为字典:
old = dict(old) # if you do go for this approach be sure to build these
new = dict(new) # variables as dictionaries, not convert them each time
removed = {k:old[k] for k in old.keys() - new.keys()}
added = {k:new[k] for k in new.keys() - old.keys()}
两者都转换为函数,返回ys中的项目,但不返回xs中的项目:
编辑:在我对集合了解很多之前,我就写了这篇文章。现在我推荐使用下面给出的集合的解决方案 一个解决方案:
removed = [o for o in old if o[0] not in [n[0] for n in new]]
added = [n for n in new if n[0] not in [o[0] for o in old]]
或者,如果您将数据显示为字典:
old = dict(old) # if you do go for this approach be sure to build these
new = dict(new) # variables as dictionaries, not convert them each time
removed = {k:old[k] for k in old.keys() - new.keys()}
added = {k:new[k] for k in new.keys() - old.keys()}
两者都转换为函数,返回ys中的项目,但不返回xs中的项目:
预期的结果是什么?@EifferPower您能将每个列表转换成按id索引的字典吗?您描述的@EifferPower操作都是集合操作。尝试使用集合重新构建算法。预期结果是什么?@EifferPower能否将每个列表转换为按id索引的词典?您描述的@EifferPower操作都是集合操作。试着用集合重铸你的算法。这真的很漂亮。我不知道集合运算是这样工作的。一定要爱蟒蛇!这真是太美了。我不知道集合运算是这样工作的。一定要爱蟒蛇!