2024-09-29 21:32:42 发布
网友
我有一个字典,其中有几个值我想保持不变,但我需要在不同的键之间旋转它们。是否有一个内置的函数或外部库可以做到这一点,还是我自己编写整个程序会更好?在
我想做的事情的例子:
>>> firstdict = {'a':'a','b':'b','c':'c'} >>> firstdict.dorotatemethod() >>> firstdict {'a':'b','b':'c','c':'a'} >>>
我不必按顺序排列,我只需要每次将值关联到不同的键。在
>>> from itertools import izip >>> def rotateItems(dictionary): ... if dictionary: ... keys = dictionary.iterkeys() ... values = dictionary.itervalues() ... firstkey = next(keys) ... dictionary = dict(izip(keys, values)) ... dictionary[firstkey] = next(values) ... return dictionary ... >>> firstdict {'a': 'a', 'c': 'c', 'b': 'b'} >>> rotateItems(firstdict) {'a': 'b', 'c': 'a', 'b': 'c'}
相关问题 更多 >
编程相关推荐