首页 > 解决方案 > Python - 如何根据字典对数组中的值进行排序和替换

问题描述

我创建了一个从不同文件中提取数据并将其插入到数组中的数组。该数据具有不同的值 1-7 和顺序。
即一个文件可以有3行

label1
label4
label3

下一个文件可能只有

label3

另一个可能有

label7
label1
label3
label2

我创建了一个字典

Dict = {1:'label1',
        2:'label2',
        3:'label3',
        4:'label4',
        5:'label5',
        6:'label6',
        7:'label7'}

我想要

  1. 遍历数组
  2. 将每个标签设置为字典值(即如果 label4 则它 =4)
  3. 按 1-7 的顺序订购
  4. 对于缺失值,在该位置放置一个 0
  5. 对于有值的点,在那个点上放一个 1

即对于[label1,label4,label3]

  1. 用字典值替换并排序—— [1,3,4]
  2. 循环遍历数组,如果该数字丢失,则在该位置放置一个 0,其他所有内容在它所在的同一位置变为 1 - [1,0,1,1,0,0,0]

本质上,我是单热编码它。

这就是我正在尝试的,但我在某处弄乱了循环逻辑:

y_temp = []
for j in y:
    for k in y[j]:
        if y[j,k]== Dict[1]:
            y_temp[k] = y_temp[k].append('1')
            else:
                y[k] = y_temp[k].append('0')
        elif y[j,k] == Dict[2]:
            y_temp[k] = y_temp[k].append('2')
            else:
                y[k] = y_temp[k].append('0')
        elif y[j,k] == Dict[3]:
            y_temp[k] = y_temp[k].append('3')
            else:
                y[k] = y_temp[k].append('0')
        elif y[j,k] == Dict[4]:
            y_temp[k] = y_temp[k].append('4')
            else:
                y[k] = y_temp[k].append('0')
        elif y[j,k] == Dict[5]:
            y_temp[k] = y_temp[k].append('5')
            else:
                y[k] = y_temp[k].append('0')
        elif y[j,k] == Dict[6]:
            y_temp[k] = y_temp[k].append('6')
            else:
                y[k] = y_temp[k].append('0')
        elif y[j,k] == Dict[7]:
            y_temp[k] = y_temp[k].append('7')
            else:
                y[k] = y_temp[k].append('0')

标签: pythonarraysdictionaryfor-loopappend

解决方案


您应该以另一种方式构建您的字典(即键应该是标签)。这将允许您将标签转换为索引。
要获得 1 和 0 的最终列表,您无需通过索引列表进行中间步骤,您可以直接从源数据构建该列表:

Dict = {'label1':1,
        'label2':2,
        'label3':3,
        'label4':4,
        'label5':5,
        'label6':6,
        'label7':7}


lines1 = """label1
label4
label3""".split("\n")

lines2 = """label3
label1""".split("\n")

lbl = [lines1,lines2] # <-- this is a list of lists (of strings) like yours

result = [0]+[0]*max(Dict.values())
for lineList in lbl:
    for line in lineList:
        result[Dict.get(line,0)] = 1 # <-- notice how this is using line, not lbl
result = result[1:]

print(result)
# [1, 0, 1, 1, 0, 0, 0]

推荐阅读