简体   繁体   English

将列表中的值用作另一个列表的索引的最pythonic方法

[英]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. 我有一个列表hns = [[a,b,c],[c,b,a],[b,a,c]] ,其中位置给出了特定样本中的排名。 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. hns[0]运行1 hns[1]运行`2,hns [2]运行3,而'a'在运行1中排名1,在运行2中排名3,在运行3中排名2。

and another list hnday = [[a,1,2,3],[b,1,2,3],[c,1,2,3]] 而另一个列表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 所以在hns中a处于0,0位置,然后是1,2和2,1,在这个问题上意味着它的排名分别是1 3 2,我需要得出一张表来反映这一点

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 所以现在(由于我是python的新手,因为我仍然陷入循环思维之中)在我看来,我必须遍历hns并填充hnday因为我要使用'a'= 1的索引值,并且更新hnday[0][1] = 1 hnday[0][2] = 3hnday[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: 这是我能想到的最pythonic和最漂亮的方式:

>>> 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 . 使用字典,您可以使用hnday[key]轻松访问键的排名,而不是迭代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]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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