Python—如何基于字典对数组中的值进行排序和替换
我创建了一个数组,从不同的文件中提取数据并将其插入数组中。该数据的值1-7和顺序不同。Python—如何基于字典对数组中的值进行排序和替换,python,arrays,dictionary,for-loop,append,Python,Arrays,Dictionary,For Loop,Append,我创建了一个数组,从不同的文件中提取数据并将其插入数组中。该数据的值1-7和顺序不同。 i、 e.一个文件可以有3行 label1 label4 label3 下一个文件可能只有 label3 而另一个可能已经 label7 label1 label3 label2 我已经编了一本字典 Dict = {1:'label1', 2:'label2', 3:'label3', 4:'label4', 5:'label5',
i、 e.一个文件可以有3行
label1
label4
label3
下一个文件可能只有
label3
而另一个可能已经
label7
label1
label3
label2
我已经编了一本字典
Dict = {1:'label1',
2:'label2',
3:'label3',
4:'label4',
5:'label5',
6:'label6',
7:'label7'}
我想
[label1,label4,label3]
[1,3,4]
[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]
Dict={'label1':1,
“标签2”:2,
“label3”:3,
“label4”:4,
“label5”:5,
“label6”:6,
“label7”:7}
lines1=“”标签1
标签4
标签3“.”。拆分(“\n”)
lines2=“”标签3
标签1“.”。拆分(“\n”)
lbl=[lines1,lines2]#我同意@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)
输出:
[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]]
请用运行程序时得到的完整错误回溯更新您的问题。我可以看到,正如您的代码一样,它工作得非常出色。然而,当我把它放在我的代码中时,我得到了这个错误,它没有意义。结果[Dict.get(lbl,0)]=1类型错误:不可损坏类型:“list”预期类型“str”(匹配的泛型类型“_KT”),获取“list[str]”而不是标题我怀疑您的lbl变量不是字符串而是字符串列表。您的变量不也是吗?`lbl={list:3}['label1','label5','label4']0={str}'label1'1={str}'label5'2={str}'label4'len={int}3`lbl={list:3}['label1',label5',label4']
告诉我lbl是一个字符串列表。在我的示例中,我将遍历for循环中字符串列表(称为行)的每一项,因此我的label变量是一个字符串。