【问题标题】:Simpler solution to find changes in lists with dicts使用字典查找列表更改的更简单解决方案
【发布时间】:2014-10-01 09:15:05
【问题描述】:

我正在寻找一种更好、更简单的解决方案来查找字典、存档数据和实际数据中的两个嵌套列表之间的变化。

我要找:

  • 在实际数据中添加数据

  • 从实际数据中删除数据

  • 更改内部数据 - 按id 值搜索(数据的唯一编号)

self.l_dicts_arch - 存档数据

self.l_dicts_actual - 实际数据

这是我的功能:

def check(self):
    for item in self.l_dicts_arch: 
        if item in self.l_dicts_actual:#remove correct data
            self.l_dicts_actual.remove(item) 
        elif item not in l_dicts_actual:
            for item2 in l_dicts_actual:
                if item['id']==item2['id']:#display and remove data with error
                    print 'Found error in data'
                    print 'from first list', item
                    print 'from second list',item2
                    actual_list.remove(item2)
                else:
                    print 'This item was removed from actual list'#display deleted data
                    print item
    if len(self.l_dicts_actual)!=0:
        print 'This item was added on actual list'
        for item in self.l_dicts_actual:
            print item

【问题讨论】:

标签: python python-2.7


【解决方案1】:

适用于以下套装:

actual = [{'id' : 4, 'data' : 'foo'}, {'id' : 5, 'data' : 'toto'}, {'id' : 7, 'data' : 'tagada'}] arch = [{'id' : 4, 'data' : 'foo'}, {'id' : 5, 'data' : 'toto2'}, {'id' : 6, 'data' : 'tata'}]

这里有一些解决方案:

  • 项目已删除(在“id”标签上找到):

deleted = filter(lambda x: not x['id'] in map(lambda x: x['id'], actual), arch)

  • 添加数据(在“id”标签上查找):

added = filter(lambda x: not x['id'] in map(lambda x: x['id'], arch), actual)

  • 修改项目:

modified = filter(lambda x: not x in arch, filter(lambda x: x['id'] in map(lambda x: x['id'], arch), actual))

一个很酷的代码可能是这样的:

def check(arch, actual): id_actual = map(lambda x: x['id'], actual) id_arch = map(lambda x: x['id'], arch) deleted = filter(lambda x: not x['id'] in id_actual, arch) added = filter(lambda x: not x['id'] in id_arch, actual) modified = filter(lambda x: not x in arch, filter(lambda x: x['id'] in id_arch, actual))

编辑:我认为您可以优化它,我正在寻找另一种解决方案...

【讨论】:

  • 谢谢你,你的解决方案现在对我很有帮助,但如果你找到更好的解决方案,请粘贴到这里:-)
  • 我认为您可以在此代码中修补一些内容:如果您知道列表中的少数元素将被修改,您可以在检查功能的顶部添加如下内容:actual, arch = filter(lambda x: x not in arch, actual), filter(lambda x: x not in actual, arch) 那将减少很多治疗。我也在寻找别的东西。
  • 我也是filter、map 和lambda 的粉丝,但我认为您也可以通过更简单的列表声明来做到这一点...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-06
  • 1970-01-01
  • 1970-01-01
  • 2023-02-22
  • 2023-03-09
  • 2014-08-15
相关资源
最近更新 更多