Python在字典中倒序

2024-04-20 03:39:08 发布

您现在位置:Python中文网/ 问答频道 /正文

A = {0:{'a':1,'b':7, 'weight':0.6}, 
     1:{'a':5,'b':5, 'weight':0.3}, 
     2:{'a':4,'b':6, 'weight':0.1}}

我想根据值b的逆序将inverse_weight分配给每个子字典

这些b值的顺序是

   A[1]['b']  < A[2]['b'] < A[0]['b']
       5      <     6     <    7

它们的重量分别是

      0.6          0.3         0.1    

因此,我需要反转它们的重量:

      0.1          0.3         0.6

期望的A应该是

A = {0:{'a':1,'b':7, 'weight':0.6, 'inverse_weight':0.1}, 
     1:{'a':5,'b':5, 'weight':0.3, 'inverse_weight':0.6}, 
     2:{'a':4,'b':6, 'weight':0.1, 'inverse_weight':0.3}}

我不知道如何对这些b进行排序,并反向应用于inverse_weight。你知道吗


Tags: 字典排序顺序weight重量inverse逆序
3条回答

您当前列出的欲望权重不正确,因为[1, 2, 0]的权重应该是[0.3, 0.1, 0.6]。但是,当使用上面列出的正确权重时,可以使用下面的代码来获得结果:

A = {0:{'a':1,'b':7, 'weight':0.6}, 
 1:{'a':5,'b':5, 'weight':0.3}, 
 2:{'a':4,'b':6, 'weight':0.1}}
new_a = {a:b['weight'] for a, b in A.items()}
inverses = [new_a[c] for _, c in sorted([(A[i]['b'], i) for i in A], key=lambda x:x[0])]
final_inverses = dict(zip([c for _, c in sorted([(A[i]['b'], i) for i in A], key=lambda x:x[0])], inverses[::-1] if not len(inverses)%2 else inverses[len(inverses)//2+1:] +[inverses[len(inverses)//2]] + inverses[:len(inverses)//2]))
final_data = {a:{**b, **{'inverse_weight':final_inverses[a]}} for a, b in A.items()}

输出:

{0: {'weight': 0.6, 'b': 7, 'a': 1, 'inverse_weight': 0.3}, 1: {'weight': 0.3, 'b': 5, 'a': 5, 'inverse_weight': 0.6}, 2: {'weight': 0.1, 'b': 6, 'a': 4, 'inverse_weight': 0.1}}

方法

  • 创建对的列表(A[id]['b'], id)
  • 排序此列表
  • 按相反顺序添加反向权重

代码

lpairs = [(A[id]['b'], id) for id in A]
lpairs.sort()
for i in range(len(lpairs)):
    A[lpairs[i][1]]["inverted_weight"] = A[lpairs[len(lpairs)-1-i][1]]["weight"]

示例:

对于数据:

A = {0:{'a':1,'b':7, 'weight':0.6}, 
     1:{'a':5,'b':5, 'weight':0.3}, 
     2:{'a':4,'b':6, 'weight':0.1}}

这将提供:

{0: {'a': 1, 'weight': 0.6, 'b': 7, 'inverted_weight': 0.3},
 1: {'a': 5, 'weight': 0.3, 'b': 5, 'inverted_weight': 0.6},
 2: {'a': 4, 'weight': 0.1, 'b': 6, 'inverted_weight': 0.1}}

NB:

你在问题中给出的例子是不正确的,因为你说A[1]的权重是0.6,但它是0.3。你知道吗

看起来是在一个方法中使用zipsortedreversed的好借口。你知道吗

A = {0: {'a': 1, 'b': 7, 'weight': 0.6},
     1: {'a': 5, 'b': 5, 'weight': 0.3},
     2: {'a': 4, 'b': 6, 'weight': 0.1}}

# Make sorted list from A.items(), sorted by weight:
a_list = sorted(list(A.items()), key=lambda item: item[1]['weight'])

# Make a reversed copy of that list:
b_list = reversed(A_list)

A = {}
for a_item, b_item in zip(a_list, b_list):
    a_item[1]['inverse_weight'] = b_item[1]['weight']
    A[a_item[0]] = a_item[1]

相关问题 更多 >