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. 将每个标签设置为字典值(即,如果标签4,则它=4(
  3. 按1-7的顺序排列
  4. 对于缺失的值,在该位置加一个0
  5. 对于有值的点,在该点上加一个1

[label1,label4,label3]

  1. 替换为dictionary值并排序--[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的最终列表,您不需要通过索引列表的中间步骤,您可以直接从源数据构建该列表:

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.然而,如果你想保持原样:

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]

每个版本的解决方案都有一点不太正确。我最终创建了一个将两者的一些组件结合在一起的解决方案。感谢@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]]

最新更新