python获取列表中数字开始和结束的位置的索引

时间:2019-07-31 12:48:29

标签: python list

我有一个query,它是数字列表。我想获取出现数字1的索引范围。范围从1出现开始,到没有出现的索引结束。我举了一个例子来说明这一点。

query= [0,0,0,0,0,1,1,1,0,1,0,0,1,1,0]

answer = [[5,8],[9,10],[12,14]]

注意:我不是在Python列表中寻找某个值的第一个和最后一个索引。我正在寻找它们开始和结束的所有地方。

更新:从下面的一些建议答案中,看来 Itertools 对此非常方便。

6 个答案:

答案 0 :(得分:2)

您也可以使用itertools.groupby。使用enumerate获取索引,然后使用groupby实际值,然后按值过滤,最后从组中获取第一个索引和最后一个索引。

>>> from itertools import groupby
>>> query = [0,0,0,0,0,1,1,1,0,1,0,0,1,1,0]
>>> [(g[0][0], g[-1][0]+1) for g in (list(g) for k, g in
...   groupby(enumerate(query), key=lambda t: t[1]) if k == 1)]
...
[(5, 8), (9, 10), (12, 14)]

答案 1 :(得分:2)

您可以使用library(dplyr) df %>% group_by(seq) %>% filter(choose =="T") %>% top_n(1) %>% mutate(choose = "T") df[is.na(df)] <- "F 来执行此操作。

itertools.dropwhile

答案 2 :(得分:1)

query= [0,0,0,0,0,1,1,1,0,1,0,0,1,1,0]
first = 0 # Track the first index in the current group
ingroup = False # Track whether we are currently in a group of ones
answer = []
for i, e in enumerate(query):
    if e:
        if not ingroup:
            first = i
    else:
        if ingroup:
            answer.append([first, i])
    ingroup = e
if ingroup:
    answer.append([first, len(query)])
>>> answer
[[5, 8], [9, 10], [12, 14]]

我认为您可能想要这样的东西。

答案 3 :(得分:1)

您可以只使用基本的for循环和if语句在哪里检查 其中“ 0”系列变为“ 1”系列,反之亦然

query= [0,0,0,0,0,1,1,1,0,1,0,0,1,1,0]

r_0 = []
r_1 = []

for i in range(len(query)-1):
    if query[i] == 0 and query[i+1] == 1:
        r_0.append(i+1) # [5, 9, 12]
    if query[i] == 1 and query[i + 1] == 0:
        r_1.append(i + 1) # [8, 10, 14]

print (list(zip(r_0,r_1)))

输出:

[(5, 8), (9, 10), (12, 14)]

答案 4 :(得分:1)

希望这会有所帮助。这是一个没有foor循环的解决方案

from itertools import chain

query = [0,0,0,0,0,1,1,1,0,1,0,0,1,1,0]

result = list(zip(
    filter(lambda i: query[i] == 1 and (i == 0 or query[i-1] != 1), range(len(query))),
    chain(filter(lambda i: query[i] != 1 and query[i-1] == 1, range(1, len(query))), [len(query)-1])
))
print(result)

输出为:

[(2, 3), (5, 8), (9, 10), (12, 14)]

答案 5 :(得分:0)

想分享一种递归方法

query= [0,0,0,0,0,1,1,1,0,1,0,0,1,1,0]

def findOccurrences(of, at, index=0, occurrences=None):
    if occurrences == None: occurrences = [] # python has a weird behavior over lists as the default
                                           # parameter, unfortunately this neets to be done

    try:
        last = start = query.index(of, index)

        for i in at[start:]:
            if i == of:
                last += 1
            else:
                break

        occurrences.append([start, last])
        return findOccurrences(of, at, last, occurrences)
    except:
        pass
    return occurrences


print(findOccurrences(1, query))
print(findOccurrences(1, query, 0)) # Offseting
print(findOccurrences(0, query, 9)) # Offseting with defaul list