lis第三部分的第一个索引号

2024-04-20 08:33:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我的清单由三部分组成。在第一和第三部分,所有的要素都是真实的。在第二部分,所有的元素都是假的。你知道吗

我想知道第三部分的第一个索引。你知道吗

例如,在执行下面的代码之后显示5。如何在下面的代码中实现get_first_index_of_third_part?我想我应该用numpy,找不到怎么用。你知道吗

three_parts_list = [True, True, False, False, False, True, True, True]
ind = get_first_index_of_third_part(three_parts_list)
print(ind)

Tags: of代码falsetrue元素getindexlist
3条回答

在列表上循环,将每个元素与前一个元素进行比较:

def get_first_index_of_third_part(three_parts_list, part=3):
    current_part = 0
    old = None
    for i, el in enumerate(three_parts_list):
        if el != old:
            # New part found
            current_part += 1
        # Stop at the beginning of the correct part
        if current_part == part:
            return i
        # Keep record of previous element
        old = el

这里,part函数的get_first_index_of_third_part参数决定了部分的数量,默认值为3。你知道吗

您可以通过迭代数组来实现这一点

def get_first_index_of_third_part(l):
    # assuming the three parts always exists.
    for i in range(1,len(l)):
        if not l[i-1] and l[i]:
            return i

如果你说这三个部分一直存在,我们可以通过将真值和假值转换成int来使用^{}^{},即

def gfi_third(x): 
    return (np.diff(x.astype(int)) > 0).argmax() + 1

运行示例:

three_parts_list = np.array([True, False, False, False, False, False,True, True])
three_parts_list2 = np.array([True, False, False, False, True, True,True, True])

gfi_third(three_parts_list)
6 

gfi_third(three_parts_list2)
4

相关问题 更多 >