Python中2維數組/矩陣轉化為字典(矩陣中第一列含有重復元素)??


例如將a=[[3,789],[1,100],[1,102],[2,102],[1,106],[2,456]];轉化為一個字典b={1:[100,102,102],2:[102,456],3:[789]}

如果用強制轉換:

1 >>> a=[[3,789],[1,100],[1,102],[2,102],[1,106],[2,456]];
2 >>> b=dict(a)
3 >>> b
4 {1: 106, 2: 456, 3: 789}
5 >>> 

結果顯然刪除了字典中重復鍵所對應的值;

 1 # 將列表轉化為字典
 2 def listTodict():
 3     a=[[3,789],[1,100],[1,102],[2,102],[1,106],[2,456]];
 4     lenArr=len(a);
 5     # 列出第一列所有的元素值,包含重復元素
 6     firstCol=[];
 7     for i in range(lenArr):
 8         firstCol.append(a[i][0]); # [3, 1, 1, 2, 1, 2]
 9     # 列出第一列所有的不重復元素
10     firstColNotRep=set(firstCol);    # {1,2,3}集合中元素沒有順序
11     firstColNotRep=list(firstColNotRep); # firstColNotRep=[1,2,3]
12     # 統計第一列所有的不重復元素的個數
13     lenfirstColNotRep=len(firstColNotRep);
14     b=[];c=[];
15     for i in range(lenfirstColNotRep):
16         b.append([firstColNotRep[i]]);  # [[1], [2], [3]]
17     for i in range(lenfirstColNotRep): 
18         for j in range(lenArr):
19             if firstColNotRep[i]==a[j][0]: # firstColNotRep=[1,2,3]
20                 print(j);
21                 b[i].append(a[j][1]);
22     return b;
23 # 結果b=[[1,100,102,106],[2,102,456], [3,789]]
24 
25 # 怎樣將[1,100,102,106]先轉為[1,[100,102,106]]轉化為[1:[100,102,106]]
26 def listToDict1():
27     d=[[1,100,102,106],[2,102,456], [3,789]];
28     e={};
29     for i in range(len(d)):
30         e[d[i][0]]=d[i][1:];
31     return e;
32     

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM