How to report an error if an element is missing in the list of lists

前端 未结 2 774
耶瑟儿~
耶瑟儿~ 2021-01-28 16:22

suppose

list1 = [[\'a\', (1, 1)], [\'a\', (1, 3)], [\'a\', (1, 4)], [\'b\', (2,1)], [\'b\', (2,2)], [\'b\',(2, 4)]]

list2 = [[(1, 1), (1, 3), (2, 1), (2, 2), (         


        
2条回答
  •  攒了一身酷
    2021-01-28 16:36

    from collections import defaultdict
    set1 = set(list1)
    set2 = set(list2)
    missing = []
    dict1 = defaultdict(lambda: defaultdict(list))
    dict2 = defaultdict(list)
    for key, sublist in set1:
        dict1[key][sublist[0]].append(sublist[1])
    for key, value in set2:
        dict2[key].append(value)
    for key, subdict in sorted(dict1.iteritems()):
        for subkey, values in sorted(subdict.iteritems()):
            subkey_misses = []
            last_value = None
            for value in values:
                if last_value is not None and last_value + 1 != value:
                    subkey_misses.extend(range(last_value + 1, value))
                last_value = value
            if subkey_misses:
                misses.append('%s.%d missing %s' % (key, subkey, subkey_misses))
    for key, values in sorted(dict2.iteritems()):
        key_misses = []
        last_value = None
        for value in values:
            if last_value is not None and last_value + 1 != value:
                key_misses.append(range(last_value + 1), value))
            last_value = value
        if key_misses:
            misses.append('%d missing %s' % (key, key_misses))
    print misses
    

提交回复
热议问题