我必须定义一个将字典键值移动n = 1的函数。
例如:
input : {'A' : 'A', 'B' : 'B', 'C' : 'C'}
output : {'A' : 'B', 'B' : 'C', 'C' : 'A'}
这是我尝试过的:
dictionary = {'A' : 'A', 'B' : 'B', 'C' : 'C'}
def shift(dictionary, n):
n=1
for i in range (0,int(len(dictionary)/2)):
dictionary[list(dictionary)[i]], dictionary[list(dictionary)[len(dictionary)-i-1]] = dictionary[list(dictionary)[len(dictionary)-i-1]], dictionary[list(dictionary)[i]]
return shift
有人向我解释必须转移n = 1,我只知道如何将值更改为随机,而不是被一个人完全移动。
如果您使用的是Python 3.7或更高版本,其中dict键是有序的,您可以使用带有dict值的itertools.cycle
来允许值环绕,并使用itertools.islice
将值移动给定的数字,以便它们可以压缩为使用dict
构造函数构造新dict的关键:
from itertools import cycle, islice
def shift(d, n):
return dict(zip(d, islice(cycle(d.values()), n, None)))
所以shift({'A' : 'A', 'B' : 'B', 'C' : 'C'}, 1)
回归:
{'A': 'B', 'B': 'C', 'C': 'A'}
并且shift({'A' : 'A', 'B' : 'B', 'C' : 'C'}, 2)
回归:
{'A': 'C', 'B': 'A', 'C': 'B'}
如果您使用的是早期的Python版本,则可以使用collections.OrderedDict
代替dict。