列表第三部分的第一个索引号

时间:2017-10-23 14:11:51

标签: python list numpy

我有一份由三部分组成的清单。在第一和第三部分中,所有元素都是True。在第二部分中,所有元素都是假的。

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

例如,执行以下代码后会显示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)

5 个答案:

答案 0 :(得分:2)

如果您说这三个部分一直存在,我们可以np.diff()使用argmax()转换True& 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

答案 1 :(得分:0)

遍历列表,将每个元素与前一个元素进行比较:

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.

答案 2 :(得分:0)

你可以通过遍历数组

来实现这一点
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

答案 3 :(得分:0)

检查列表中的项目为False的第一个实例,下一个项目为True

def get_first_index_of_third_part(three_parts_list):
    for i in range(len(three_parts_list)-1):
        if three_parts_list[i] == False and three_parts_list[i+1] == True:
            print(i)

答案 4 :(得分:-1)

查找第三部分开头索引的算法是:

  1. 将列表拆分为部分
  2. 添加前两部分的长度
  3. 可以使用itertools.groupbyitertools.islice

    来完成
    parts = itertools.groupby(three_parts_list)
    result = sum(len(list(items)) for _, items in itertools.islice(parts, 2))