从python中的另一个列表中获取列表的索引

时间:2013-11-19 08:35:25

标签: python list

我有两个这样的列表:

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

使用b我希望得到如下结果:

a -> 0, 2, 5
b -> 1, 4
c -> 3
d -> 6

尝试使用enumerate()

>>> for i, j in enumerate(b):
...     a[i]
... 
'a'
'b'
'a'
'c'

没用。

8 个答案:

答案 0 :(得分:5)

You were right to use enumerate, though you didn't quite use it exactly right

In [5]: a = ['a', 'b', 'a', 'c', 'b', 'a', 'd']

In [6]: b = ['a', 'b', 'c', 'd']

In [7]: for char in b: print char, [i for i,c in enumerate(a) if c==char]
a [0, 2, 5]
b [1, 4]
c [3]
d [6]

答案 1 :(得分:0)

尝试

>>> a = ['a', 'b', 'a', 'c', 'b', 'a', 'd']
>>> b = ['a', 'b', 'c', 'd']
>>> indices = [ i for i, x in enumerate(a) if x == b[0] ]
>>> indices
[0, 2, 5]

您可以将b[0]更改为您希望索引的任何字母。

说明:

让枚举(a)的每个元素都是(i,x)形式。 因此,indices是枚举(a)中所有i的数组,使x等于b[0](或者您想要的任何其他字母)。

答案 2 :(得分:0)

def get_all_indexes(lst, item):
    return [i for i, x in enumerate(lst) if x == item]

a = ['a', 'b', 'a', 'c', 'b', 'a', 'd']
b = ['a', 'b', 'c', 'd']

for item in b:
    print item, get_all_indexes(a, item)

结果:

>>> 
a [0, 2, 5]
b [1, 4]
c [3]
d [6]

答案 3 :(得分:0)

我会这样做......

代码:

a = ['a', 'b', 'a', 'c', 'b', 'a', 'd']
b = ['a', 'b', 'c', 'd']

for item in b:
    print item + ':' + ','.join([str(i) for i,val in enumerate(a) if item==val])   

输出

a:0,2,5
b:1,4
c:3
d:6  

希望这会有所帮助:)

答案 4 :(得分:0)

>>> [(char, [i for i,c in enumerate(a) if c==char]) for char in b]
[('a', [0, 2, 5]), ('b', [1, 4]), ('c', [3]), ('d', [6])]

>>> dict((char, [i for i,c in enumerate(a) if c==char]) for char in b)
{'a': [0, 2, 5], 'c': [3], 'b': [1, 4], 'd': [6]}

答案 5 :(得分:0)

import collections
def getIndex(ListA, ListB):
    res = collections.defaultdict(list)
    for element in ListB:
        for (i, v) in enumerate(ListA):
            if element == v:
                res[v].append(i)

    for key, value in sorted(res.items(), key = lambda d : d[0]):
        print(key, " -> ", ",".join([str(i) for i in value]))

a = ['a', 'b', 'a', 'c', 'b', 'a', 'd']
b = ['a', 'b', 'c', 'd']
getIndex(a, b)

输出结果为:

a  ->  0,2,5
b  ->  1,4
c  ->  3
d  ->  6

答案 6 :(得分:0)

感谢所有枚举:),这里有一些非常有趣的东西,我上次尝试回答一些相同的东西,即使用index()函数返回多个位置。

a = ['a', 'b', 'a', 'c', 'b', 'a', 'd']
b = ['a', 'b', 'c', 'd']
for item in b:
    index = []
    start = -1
    while True:
        #also take care of the case where item in b is not in a
        try:
            start = a.index(item, start+1)
            index.append(start)
        except ValueError:
            break;
        print item, index

结果

a [0, 2, 5]
b [1, 4]
c [3]
d [6]

a.index(b, position)定义了索引的起点。

答案 7 :(得分:0)

O(n+m)算法(许多其他答案似乎都有O(n*m)复杂度):

>>> from collections import defaultdict
>>> D = defaultdict(list)
>>> for i,item in enumerate(a): D[item].append(i)  
>>> for item in b:
    print('{} -> {}'.format(item, D[item]))   

a -> [0, 2, 5]
b -> [1, 4]
c -> [3]
d -> [6]