根据其值反转字典的部分
Reversed parts of a dictionary according to its values
我是 Python 的新手,我正在尝试使用词典进行不同的尝试。我有疑惑如何将前面所有项的顺序倒序为一个值大于10
的项
Input: [1 : value1, 2 : value2, 3 : value3, 4 : value4], knowing that (value3 * 2) > 10
Output : [1 : value2, 2 : value1, 3 : value3, 4 : value4]
结合字典中的真实例子:
Input : {0: 1, 1: 4, 2: 6, 3: 1, 4: 2}
Output : {0: 4, 1: 1, 2: 6, 3: 1, 4: 2}
如果有多个数字,我希望每组项目都反转:
Input : {0: 1, 1: 4, 2: 6, 3: 2, 4: 1, 5: 6, 6: 1, 7: 2}
Output : {0: 4, 1: 1, 2: 6, 3: 1, 4: 2, 5: 6, 6: 1, 7: 2}
您似乎混淆了集合和列表。如果是列表,解决方案将是:
def map_reverse_partial(A):
start = 0
for index, ele in enumerate(A):
if 2 * ele >= 16:
A[start:index + 1] = reversed(A[start:index + 1])
start = index + 1
return A
如果是地图,解决方案将是:
def map_reverse_partial(A):
start = 0
for index, ele in enumerate(A.values()):
if 2 * ele > 10:
if index > start + 1:
for i in range(start, (start + index - 1)//2 + 1):
A[i], A[start + index - 1 - i] = A[start + index - 1 - i], A[i]
start = index + 1
return A
def swapper(d):
keys = []
values = []
for p in d:
if p*d[p] > 10:
values.reverse() # reverse the order of values
for k,v in zip(keys, values): # update values
d[k] = v
keys = [] # empty the keys and values lists
values = []
else: # keep track of the things we will need to swap
keys.append(p)
values.append(d[p])
return d
我是 Python 的新手,我正在尝试使用词典进行不同的尝试。我有疑惑如何将前面所有项的顺序倒序为一个值大于10
的项Input: [1 : value1, 2 : value2, 3 : value3, 4 : value4], knowing that (value3 * 2) > 10
Output : [1 : value2, 2 : value1, 3 : value3, 4 : value4]
结合字典中的真实例子:
Input : {0: 1, 1: 4, 2: 6, 3: 1, 4: 2}
Output : {0: 4, 1: 1, 2: 6, 3: 1, 4: 2}
如果有多个数字,我希望每组项目都反转:
Input : {0: 1, 1: 4, 2: 6, 3: 2, 4: 1, 5: 6, 6: 1, 7: 2}
Output : {0: 4, 1: 1, 2: 6, 3: 1, 4: 2, 5: 6, 6: 1, 7: 2}
您似乎混淆了集合和列表。如果是列表,解决方案将是:
def map_reverse_partial(A):
start = 0
for index, ele in enumerate(A):
if 2 * ele >= 16:
A[start:index + 1] = reversed(A[start:index + 1])
start = index + 1
return A
如果是地图,解决方案将是:
def map_reverse_partial(A):
start = 0
for index, ele in enumerate(A.values()):
if 2 * ele > 10:
if index > start + 1:
for i in range(start, (start + index - 1)//2 + 1):
A[i], A[start + index - 1 - i] = A[start + index - 1 - i], A[i]
start = index + 1
return A
def swapper(d):
keys = []
values = []
for p in d:
if p*d[p] > 10:
values.reverse() # reverse the order of values
for k,v in zip(keys, values): # update values
d[k] = v
keys = [] # empty the keys and values lists
values = []
else: # keep track of the things we will need to swap
keys.append(p)
values.append(d[p])
return d