Python-如何基于字典对数组中的值进行排序和替换

问题描述 投票:0回答:3

我创建了一个数组,该数组从其他文件中提取数据并将其插入到数组中。此数据的值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')
python arrays dictionary for-loop append
3个回答
1
投票

您应该以其他方式构建字典(即键应该是标签)。这将允许您将标签转换为索引。要获得最终的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]

0
投票

我同意@Alain T.最好颠倒Dict。但是,如果您想保持原样:

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

lables_arr=['label1','label4','label3']        

nums_arr=[]
for x,y in Dict.items():
    for z in lables_arr:
        if z==y:
            nums_arr.append(x)

nums_arr.sort()

final=[]
for i in range(len(Dict)):
    if i not in nums_arr:
        final.append(0)
    else:
        final.append(1)

print(final)

输出:

[0, 1, 0, 1, 1, 0, 0]


0
投票

每个版本的解决方案都有一点不太正确。我结束了创建一个将两者的某些部分组合在一起的解决方案。感谢@Alain T和@Phineas提供的出色解决方案和对我问题的回答。没有你们一个,我做不到。谢谢!!

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

labels_arr = [['label1', 'label5', 'label4'], ['label1', 'label4', 'label3'], 
             ['label1', 'label3'], ['label1'], ['label1', 'label4', 'label3'], 
             ['label1', 'label3', 'label4'], 
             ['label1', 'label2', 'label3', 'label4', 'label5', 'label6', 'label7']]

nums_arr  =[]                      # this array saves the list after each loop
for i in range(len(labels_arr)):   # needed first to loop through the list of lists
    nums_arr_i=[]                  # this array needed to append the 1's and 0's to it
    for key in Dict.keys():        # after we loop through the Dict keys first
        if key in labels_arr[i]:   # compares the keys to original labels array at [i]
            nums_arr_i.append(1)   # append 1 or 0 if it matches or not
        else:
            nums_arr_i.append(0)
    nums_arr.append(nums_arr_i)    # end result list of 7 1's or 0's is appended to 
print('nums_arr= ', nums_arr)      # nums_arr and we loop to the next i in labels_arr

# End Result
nums_arr=  [[1, 0, 0, 1, 1, 0, 0], [1, 0, 1, 1, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], 
           [1, 0, 0, 0, 0, 0, 0], [1, 0, 1, 1, 0, 0, 0], [1, 0, 1, 1, 0, 0, 0], 
           [1, 1, 1, 1, 1, 1, 1]]
© www.soinside.com 2019 - 2024. All rights reserved.