gpt4 book ai didi

python - 在python列表中获取连续性第一次中断的索引

转载 作者:太空宇宙 更新时间:2023-11-04 00:07:42 27 4
gpt4 key购买 nike

假设 python 列表是;my_list = [0,0,0,0,0,1,1,0,0]

0s 的顺序在列表的索引位置 5 发生变化。有没有办法在列表中第一次更改序列时返回索引?

最佳答案

只需使用 index 方法即可。

my_list = [0,0,0,0,0,1,1,0,0]

my_list.index(1)
>> 5

假设您的列表中只有二进制元素,.index 返回您在列表中查找的元素的最低索引,并且等同于序列更改时的索引。

或者,如果它们只是一个数字序列,您可以定义一个辅助函数,通过将它与第一个值进行比较来按顺序返回第一个中断。

def changed(li):
start = li[0]
change = [i for i in li if i != start][0]
return li.index(change)

another_list = [1,1,1,0,1,1,1,1]
idx = changed(another_list)

print('index of sequence change: {}\nvalue of sequence change: {}'.format(idx,another_list[idx]))

>>
index of sequence change: 3
value of sequence change: 0

关于python - 在python列表中获取连续性第一次中断的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53494107/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com