gpt4 book ai didi

python - 如何从 python 列表中获取零值和非零值的索引范围?

转载 作者:行者123 更新时间:2023-11-28 21:37:46 25 4
gpt4 key购买 nike

我有一个包含零值和非零值的列表。我想根据列表中的元组找到零值和非零值的范围。我正在寻找使用 pythonic 方式的无包解决方案。例如。

a = [ 0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   5,  11,  12,
12, 12, 13, 13, 17, 17, 17, 17, 17, 17, 17, 17, 17,
25, 42, 54, 61, 61, 68, 73, 103, 115, 138, 147, 170, 187,
192, 197, 201, 208, 210, 214, 216, 217, 217, 218, 219, 220, 221,
222, 222, 219, 220, 220, 221, 220, 216, 216, 217, 217, 217, 217,
216, 216, 216, 209, 204, 193, 185, 177, 161, 156, 143, 110, 103,
89, 82, 62, 62, 62, 60, 56, 55, 50, 49, 48, 47, 47,
45, 44, 43, 42, 40, 37, 23, 22, 14, 12, 6, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
6, 6, 6, 7, 7, 7, 13, 29, 31, 32, 33, 41, 42,
43, 43, 44, 44, 44, 44, 44, 60, 70, 71, 72, 88, 95,
104, 105, 111, 124, 125, 131, 145, 157, 169, 174, 186, 190, 190,
191, 192, 192, 193, 193, 193, 194, 198, 201, 202, 203, 202, 203,
203, 203, 203, 203, 203, 197, 195, 186, 177, 171, 154, 153, 148,
141, 140, 135, 132, 120, 108, 94, 86, 78, 73, 60, 53, 46,
46, 45, 44, 43, 37, 35, 29, 26, 19, 11, 0]]

输出:idx = [(0,9),(10,101),(102,128),...]

最佳答案

这里是我的建议,没有外部包,简短、易读且易于理解:

# Compute list "b" by replacing any non-zero value of "a" with 1
b = list(map(int,[i != 0 for i in a]))

#Compute ranges of 0 and ranges of 1
idx = [] # result list of tuples
ind = 0 # index of first element of each range of zeros or non-zeros
for n,i in enumerate(b):
if (n+1 == len(b)) or (b[n] != b[n+1]):
# Here: EITHER it is the last value of the list
# OR a new range starts at index n+1
idx.append((ind,n))
ind = n+1

print(idx)

关于python - 如何从 python 列表中获取零值和非零值的索引范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48986755/

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