Python equivalent of zip for dictionaries

前端 未结 5 1354
迷失自我
迷失自我 2020-12-13 18:10

If I have these two lists:

la = [1, 2, 3]
lb = [4, 5, 6]

I can iterate over them as follows:

for i in range(min(len(la), le         


        
5条回答
  •  醉梦人生
    2020-12-13 18:33

    In case if someone is looking for generalized solution:

    import operator
    from functools import reduce
    
    
    def zip_mappings(*mappings):
        keys_sets = map(set, mappings)
        common_keys = reduce(set.intersection, keys_sets)
        for key in common_keys:
            yield (key,) + tuple(map(operator.itemgetter(key), mappings))
    

    or if you like to separate key from values and use syntax like

    for key, (values, ...) in zip_mappings(...):
        ...
    

    we can replace last line with

    yield key, tuple(map(operator.itemgetter(key), mappings))
    

    Tests

    from collections import Counter
    
    
    counter = Counter('abra')
    other_counter = Counter('kadabra')
    last_counter = Counter('abbreviation')
    for (character,
         frequency, other_frequency, last_frequency) in zip_mappings(counter,
                                                                     other_counter,
                                                                     last_counter):
        print('character "{}" has next frequencies: {}, {}, {}'
              .format(character,
                      frequency,
                      other_frequency,
                      last_frequency))
    

    gives us

    character "a" has next frequencies: 2, 3, 2
    character "r" has next frequencies: 1, 1, 1
    character "b" has next frequencies: 1, 1, 2
    

    (tested on Python 2.7.12 & Python 3.5.2)

提交回复
热议问题