我有一个随机生成的列表,看起来像:
[1, 0, 0, 1, 1, 0, 1, 0, 0, 0]
我需要找到1之间的所有距离,包括那些环绕的距离。
例如,上面的列表中,第一个1与下一个1的距离为3.第二个1与下一个1的距离为1,依此类推。
如何使用环绕到第一个1来找到列表中最后1个的距离?
def calc_dist(loc_c):
first = []
#lst2 = []
count = 0
for i in range(len(loc_c)):
if loc_c[i] == 0:
count += 1
#lst2.append(0)
elif loc_c[i] == 1:
first.append(i)
count += 1
loc_c[i] = count
#lst2.append(loc_c[i])
#if loc_c[i] + count > len(loc_c):
# x = loc_c[first[0] + 11 % len(loc_c)]
# loc_c[i] = x
count = 0
return loc_c
我的预期结果应该是[3,1,2,4]。
干净整洁:
def calc_dist(l):
idx = [i for i, v in enumerate(l) if v]
if not idx: return []
idx.append(len(l)+idx[0])
return [idx[i]-idx[i-1] for i in range(1,len(idx))]
print(calc_dist([1, 0, 0, 1, 1, 0, 1, 0, 0, 0]))
# [3, 1, 2, 4]
print(calc_dist([0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0]))
# [3, 1, 2, 7]
print(calc_dist([0, 0, 0, 0])
# []
存储你第一次引用的第一个1
的索引,然后当你到达最后一个1
时,你只需要在最后一个0
之后添加第一个加上1
元素的数量以获得该距离(所以len(inputlist) - lastindex + firstindex
)。
其他距离是前面的1
值和当前指数之间的差值。
from typing import Any, Generator, Iterable
def distances(it: Iterable[Any]) -> Generator[int, None, None]:
"""Produce distances between true values in an iterable.
If the iterable is not endless, the final distance is that of the last
true value to the first as if the sequence of values looped round.
"""
first = prev = None
length = 0
for i, v in enumerate(it):
length += 1
if v:
if first is None:
first = i
else:
yield i - prev
prev = i
if first is not None:
yield length - prev + first
上面的生成器在序列seq
上循环时计算距离,逐个产生它们:
>>> for distance in distances([1, 0, 0, 1, 1, 0, 1, 0, 0, 0]):
... print(distance)
...
3
1
2
4
如果你必须有列表输出,只需在生成器上调用list()
:
>>> list(distances([1, 0, 0, 1, 1, 0, 1, 0, 0, 0]))
[3, 1, 2, 4]
如果没有1
值,则会产生零距离:
>>> list(distances([0, 0, 0]))
[]
和1个1
值给你1个距离:
>>> list(distances([1, 0, 0]))
[3]
我已经使解决方案足够通用,能够处理任何可迭代的,即使是无限的;这意味着你也可以使用另一台发电机来喂它。如果给出一个产生至少一些非零值的无限迭代,它就会保持产生距离。
你可以使用numpy:
import numpy as np
L = np.array([1, 0, 0, 1, 1, 0, 1, 0, 0, 0])
id = np.where(test == 1)[0]
# id = array([0, 3, 4, 6], dtype=int64)
res = [id[i]-id[i-1] for i in range(1, len(id))]
# [3, 1, 2]
# Last distance missing:
res.append(len(L)- id[-1])
res = [3, 1, 2, 4]
请注意,您要求的信息包含在上面,但输出格式可能不正确。你真的不具体......
编辑:如何生成随机列表,将列表转换为数组
L = [1, 0, 0, 1, 1, 0, 1, 0, 0, 0]
np.asarray(L)
Edit2:如何检查列表中是否没有1:
import numpy as np
L = np.array([1, 0, 0, 1, 1, 0, 1, 0, 0, 0])
id = np.where(test == 1)[0]
if len(id) == 0:
res = []
else:
res = [id[i]-id[i-1] for i in range(1, len(id))]
res.append(len(L)- id[-1])
要么:
try:
res = [id[i]-id[i-1] for i in range(1, len(id))]
res.append(len(L)- id[-1])
except:
res = []