获取python中另一个列表中某个位置后列表中每个元素的位置

时间:2013-03-08 22:22:26

标签: python list indexing

我有一个list=[1,4,5,8]项目的位置列表。

我想使用这些位置在这些位置后找到原始列表中另一个项目的出现。

我想知道是否有一个班轮在某个位置后使用枚举并将其置于for循环中以使某个位置不断变化。

以下是一个例子:

list1=['a','b','a','c','d','b','b','a','e','b','f'] 
list2#positions of 'a'=[0,2,5]

我希望在b之后a首次出现a,而不是{{1}}之前。{/ p>

2 个答案:

答案 0 :(得分:0)

如果您需要先找到标记,然后再找到目标的第一个实例:

def find_after(lst, target, mark):
    marks = []
    while True:
        try:
            marks.append(lst.index(mark,marks[-1] if marks else 0))
        except ValueError:
            # no more 'a's were found
            break
    targets = []
    for m in marks:
        try:
            targets.append(lst.index(target, m))
        except ValueError:
            continue
    return targets

其作用如下:

find_after(['a','b','a','c','d','b','b','a','e','b','f'], 'b', 'a')
#[1,5,9] # the locations of the 'b's (target) after the 'a's (mark)

答案 1 :(得分:0)

这是一种找到它们的简单方法。对于此版本,如果未找到该值,则会引发异常。

>>> s = 'abacdaebfxxxxxxxxxxxxxxxxxxxxxabc'
>>> finder = lambda lst, inds, x: [lst.index(x, i) for i in inds]
>>> finder(s, [0, 2, 3, 10], 'a')
[0, 2, 5, 30]

如果s是字符串或列表,这将有效。