在二维数组的所有行中查找特定序列

2024-07-05 09:07:13 发布

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

我试图用python(或者更像python的方式)创建一个循环,以检测2d数组中何时发生特定序列,然后用另一个集合替换它。特别是在每一行中找到第一个[0,1,1],并将其替换为类似[0.25,0.5,0.75]的内容,以在1的边缘创建渐变

例如:

a =[[0,0,0,0,0,0,0]
    [0,1,1,1,1,1,0]
    [0,1,1,1,1,1,0]
    [0,0,0,0,0,0,0]]

detectfunction(a,[0,1,1],[0.25,0.5,0.75])

output =[[0,  0 ,  0 ,  0,0,0,0]
        [0,0.25,0.5,0.75,1,1,0]
        [0,0.25,0.5,0.75,1,1,0]
        [0,  0 ,  0 ,  0,0,0,0]]

这是我当前的代码,它只在数据的一个部分中工作。边缘列表是我在0,1转换后真正想要切入的

fr_len = 10
fringe = np.arange(0,1,1/fr_len)
fringecloud1 = []
for ind,val in enumerate(O1bitcloud_m):
    m = list(O1bitcloud_m[ind])
    if val[ind] == 0 and val[ind+1] == 1:
        startind = ind
        endind = ind+fr_len
        m[startind:endind] = fringe
        fringecloud1.append(m)
    else:
        fringecloud1.append(m)

提前谢谢你


Tags: len方式序列val数组fr边缘ind
2条回答

下面是一种使用内置array模块的方法。通过将a行表示为Python数组,我们可以直接对表示每行的字节调用replace。结果与预期的输出不完全匹配(我不确定示例输出的第2行和第3行中为什么有前导零)

a =[[0,0,0,0,0,0,0],
    [0,1,1,1,1,1,0],
    [0,1,1,1,1,1,0],
    [0,0,0,0,0,0,0],]

import array

def detectfunction(a, pattern, subst):
  pattern_bytes = array.array('d', pattern).tobytes()
  subst_bytes   = array.array('d', subst).tobytes()
  
  result = list()
  for row in a:
    arr_row = array.array('d', row)
    new_arr_row = array.array('d', [])
    new_arr_row.frombytes(arr_row.tobytes().replace(pattern_bytes, subst_bytes))
    result.append(new_arr_row.tolist())
  
  return result

result = detectfunction(a,[0,1,1],[0.25,0.5,0.75])

# [[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
#  [0.25, 0.5, 0.75, 1.0, 1.0, 1.0, 0.0],
#  [0.25, 0.5, 0.75, 1.0, 1.0, 1.0, 0.0],
#  [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]

将操作拆分为三个任务和相关方法:

  1. 获取n个连续元素的组,与目标进行比较
  2. 找到目标群体的索引,第一次匹配
  3. 用替换项替换目标组

这里的第一个方法是一个生成器,它返回一个元素按n分组的列表:

def each_cons(iterable, n = 2):
    if n < 2: n = 1
    i, size = 0, len(iterable)
    while i < size-n+1:
        yield iterable[i:i+n]
        i += 1

第二种方法是获取索引:

def find_idx_for_target(lst, target):
    for idx, sub in enumerate(each_cons(lst, n=len(target))):
        if sub == target:
            return idx
    return None

最后,替换:

def replace(lst, target, replacement):
    for sublst in lst:
        idx = find_idx_for_target(sublst, target)
        if idx is not None:
            sublst[idx:idx+len(replacement)] = replacement
    # add a check for len(target) == len(replacement)

例如:

a =[[0,0,0,0,0,0,0],
    [0,1,1,1,1,1,0],
    [0,1,1,1,1,1,0],
    [0,0,0,1,0,1,1]]
target = [0, 1, 1]
replacement = [0, 2, 2]

replace(a, target, replacement)

a

#[[0, 0, 0, 0, 0, 0, 0],
# [0, 2, 2, 1, 1, 1, 0],
# [0, 2, 2, 1, 1, 1, 0],
# [0, 0, 0, 1, 0, 2, 2]]

相关问题 更多 >