简体   繁体   中英

most pythonic way to use a value from a list as an index to another list

I have a list hns = [[a,b,c],[c,b,a],[b,a,c]] where the positions give the rank in a particular sample. ie hns[0] is run 1 hns[1] is run `2 and hns[2] is run 3 and 'a' was ranked 1 in run 1 ranked 3 in run 2 and 2 in run 3.

and another list hnday = [[a,1,2,3],[b,1,2,3],[c,1,2,3]]

so in hns a is in the 0,0 position then 1,2 and the 2,1 which in this problem means that it's ranking is 1 3 2 respectively and I need to end up with a table that reflects that

hnday = [[a,1,3,2],[b,2,2,1],[c,3,1,3]]

so right now ( because I am still stuck in for loop thinking as I am new to python) it seems to me that I have to loop through hns and populate hnday as I go taking the index value of, say 'a' = 1 and update hnday[0][1] = 1 hnday[0][2] = 3 and hnday[0][3] = 2

this doesn't seem a very pythonic way to approach this and I would ask what other approach I could look at.

This is the most pythonic and beautiful way I can think of:

>>> hns=[['a','b','c'],['c','b','a'],['b','a','c']]

>>> keys = ['a','b','c']

>>> hnday = [[k]+[hns[i].index(k)+1 for i in range(len(hns))] for k in keys]
[['a', 1, 3, 2], ['b', 2, 2, 1], ['c', 3, 1, 3]]

However, doesn't a dictionary seem most appropriate for the last expression? With a dictionary you could easily access the rankings of a key with hnday[key] , instead of iterating hnday .

It doesn't change much in the comprehension expression:

>>> hnday = {k:[hns[i].index(k)+1 for i in range(len(hns))] for k in keys}
{'c': [3, 1, 3], 'b': [2, 2, 1], 'a': [1, 3, 2]}

>>> hnday['a']
[1, 3, 2]
>>> hnday['b']
[2, 2, 1]
>>> hnday['c']
[3, 1, 3]

I think you will get a better performance if you do it this way

hns = [['a','b','c'],['c','b','a'],['b','a','c']]
M={}
for x in hns:
    for i,y in enumerate(x):
        if y in M:
            M[y].append(i+1)
        else:
            M[y]=[i+1]
print M            
# {'a': [1, 3, 2], 'c': [3, 1, 3], 'b': [2, 2, 1]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM