简体   繁体   English

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

[英]Get the index of a list from another list in python

I have two list like this: 我有两个这样的清单:

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

By using b I want to get the result like this: 通过使用b我想要得到这样的结果:

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

Tried using enumerate() 尝试使用enumerate()

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

Didn't work. 没用

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]

Try 尝试

>>> 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]

You can change b[0] to whatever letter you want the indices for. 您可以将b[0]更改为要为其索引的任何字母。

Explanation: 说明:

Let each element of enumerate(a) be of the form (i,x) . 让enumerate(a)的每个元素都具有(i,x)的形式。 So, indices is an array of all i in enumerate(a) such that x equals b[0] (or whatever other letter you want it to be). 因此, indices是enumerate(a)中所有i的数组,使得x等于b[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)

Result: 结果:

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

I ll do it like... 我会像...

Code: 码:

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])   

Output: 输出:

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

Hope this helps :) 希望这可以帮助 :)

>>> [(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])]

or 要么

>>> 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]}
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)

The output is: 输出为:

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

Thanks for all the enumerate :), here is something pretty interesting I found last time trying to answer something quite the same, that is to use index() function to return multiple positions. 感谢所有枚举:),这是我上次尝试回答完全相同的问题时发现的一些有趣的事情,那就是使用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

Result 结果

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

a.index(b, position) defines the starting point of indexing. a.index(b, position)定义索引的起点。

O(n+m) algorithm (many other answers seem to have O(n*m) complexity): 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]

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

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