簡體   English   中英

Python - 如何根據字典對數組中的值進行排序和替換

[英]Python - how to sort and replace values in an array based on a dictionary

我創建了一個從不同文件中提取數據並將其插入到數組中的數組。 此數據具有不同的值 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. 將每個 label 設置為字典值(即如果 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')

您應該以另一種方式構建您的字典(即鍵應該是標簽)。 這將允許您將標簽轉換為索引。
要獲得 1 和 0 的最終列表,您不需要通過帶有索引列表的中間步驟 go,您可以直接從源數據構建該列表:

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]

我同意@Alain T. 最好顛倒字典。 但是,如果您想保持原樣:

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)

Output:

[0, 1, 0, 1, 1, 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]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM