打印矢量名称的索引

时间:2015-04-08 01:00:46

标签: python vector indexing enumerate

我有这个载体:

 labels:  [0 5 8 6 1 3 3 2 2 5 5 6 1 1 3 3 1 8 8 3 3 1 1 1 1 5 2 5 1 1 7 3 6 4 3 3 8  1 3 3 5 1 8 8 1 8 7 1 1 8 6]

此向量有51个索引,每个索引代表一个美国州。 我有这个代码及其输出:

for j in range(9):
        print(" cluster no %i:%s"%(j,[i for i,x in enumerate(labels) if x == j]))




output:
     cluster no 0:[0]
     cluster no 1:[3, 11, 32]
     cluster no 2:[2, 17, 24, 36, 43, 49]
     cluster no 3:[1, 9, 10, 18, 25, 27, 40, 42, 45]
     cluster no 4:[6, 8, 19, 20, 26, 31, 34, 38, 39]
     cluster no 5:[21, 30, 46]
     cluster no 6:[33]
     cluster no 7:[4, 5, 12, 13, 14, 15, 16, 22, 23, 28, 29, 35, 37, 41, 44, 47, 48]
     cluster no 8:[7, 50]

基本上,输出是带有索引的值,我想打印而不是那些索引,状态,

例如,

cluster no 0:[AK]
.......

反之亦然。

所有51的索引应按顺序排列如下:

       'AK'=0
       'AL'=1 
       'AR'=2
       'AZ'=3
       'CT';...
       'DC'; 
       'DE';
       'FL';
       'GA'; 
       'HI';
       'IA';
       'ID'; 
       'IL';...
       'IN';
       'KS'; 
       'KY';
       'LA'; 
       'MA'; 
       'MD'=
       'ME'; 
       'MI';
       'MN';
       'MO';
       'MS'; 
       'MT';
       'NC'; 
       'ND'; 
       'NE';
       'NH';
       'NJ'; 
       'NM';
       'NV';
       'NY'; 
       'OH';
       'OK'; 
       'OR';
       'PA';
       'RI'; 
       'SC'; 
       'SD';
       'TN';
       'TX'; 
       'UT';
       'VA';
       'VT'; 
       'WA';
       'WI';
       'WV'; 
       'WY'= 50 ...

1 个答案:

答案 0 :(得分:0)

使用[i for i,x in...代替[states[i] for i,x in...,假设states是类似['AK', 'AL', 'AR',...的列表。您的状态列表只有49个条目,因此我添加了两个以获取指定的51。

>>> label = list(map(int, '0 5 8 6 1 3 3 2 2 5 5 6 1 1 3 3 1 8 8 3 3 1 1 1 1 5 2 5 1 1 7 3 6 4 3 3 8  1 3 3 5 1 8 8 1 8 7 1 1 8 6'.split()))
>>> states = ['AK','AL','AR','AZ','CT','DC','DE','FL','GA','HI','IA','ID','IL','IN','KS','KY','LA','MA','MD','ME','MI','MN','MO','MS','MT','NC','ND','NE','NH','NJ','NM','NV','NY','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VA','VT','WA','WI','WV','WY', 'PR', "ZZ"]
>>> for j in range(9):
...     print(" cluster no %i:%s"%(j,[states[i] for i,x in enumerate(label) if x == j]))
...
 cluster no 0:['AK']
 cluster no 1:['CT', 'IL', 'IN', 'LA', 'MN', 'MO', 'MS', 'MT', 'NH', 'NJ', 'RI', 'TX', 'VT', 'WV', 'WY']
 cluster no 2:['FL', 'GA', 'ND']
 cluster no 3:['DC', 'DE', 'KS', 'KY', 'ME', 'MI', 'NV', 'OK', 'OR', 'SC', 'SD']
 cluster no 4:['OH']
 cluster no 5:['AL', 'HI', 'IA', 'NC', 'NE', 'TN']
 cluster no 6:['AZ', 'ID', 'NY', 'AND']
 cluster no 7:['NM', 'WI']
 cluster no 8:['AR', 'MA', 'MD', 'PA', 'UT', 'VA', 'WA', 'PR']