繁体   English   中英

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

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

我有两个这样的清单:

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

没用

您使用枚举是正确的,尽管您并未完全正确地使用它

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]

尝试

>>> 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]更改为要为其索引的任何字母。

说明:

让enumerate(a)的每个元素都具有(i,x)的形式。 因此, 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)

结果:

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

我会像...

码:

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  

希望这可以帮助 :)

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

感谢所有枚举:),这是我上次尝试回答完全相同的问题时发现的一些有趣的事情,那就是使用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)定义索引的起点。

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