0

我有一个项目的位置列表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我想要aftera但不是 before的所有第一次出现a

4

2 回答 2

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)
于 2013-03-08T22:37:50.860 回答
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是字符串或列表,这将起作用。

于 2013-03-08T22:41:17.147 回答