gpt4 book ai didi

python - 如何重写一个列表列表,使 "islands"个值彼此唯一?

转载 作者:行者123 更新时间:2023-12-02 01:38:22 26 4
gpt4 key购买 nike

假设我有一个列表列表(或者概念上更准确的二维数组):

list = [[1,1,0,0,0],
[1,1,2,0,0],
[0,2,2,2,0],
[0,0,0,2,0],
[0,0,0,1,0]]

我想识别具有相同值的不同区域并重写列表,以便每个区域都有唯一的值,如下所示:

list = [[1,1,2,2,2],
[1,1,3,2,2],
[0,3,3,3,2],
[0,0,0,3,2],
[0,0,0,4,2]]

我主要尝试编写循环的变体,解析每个值的数组并将相邻值设置为彼此相等(是的,我猜这是多余的),但确保左上角的 1 岛与右下角的 1 不起作用。我的尝试往好了说是参差不齐,往坏了说是不起作用。示例:

for x in list_length:
for y in sublist_length:
try:
if list[x][y] == list[x+1][y]:
list[x+1][y] = list[x][y]
except:
pass

 predetermined_unique_value = 0

for x in list_length:
for y in sublist_length:
try:
if list[x][y] == list[x+1][y]:
list[x+1][y] = predetermined_unique_value
predetermined_unique_value += 1
except:
pass

以及要检查的方向(从当前点/点开始的上、下、左、右)的许多细微变化,通过运行循环来强制循环,直到所有点都被分配了新值,等等。

显然我在这里遗漏了一些东西。我怀疑答案实际上非常简单,但我似乎无法在 google 或 reddit 上找到任何内容,或者在这里找到其他答案(我可能只是奇怪地概念化它,所以寻找错误的东西)。

重申一下,如何解析该列表列表以根据相同的数据将值组织到相邻区域中,并重写它以确保这些区域都具有唯一值? (即只有一个 0 值区域,一个 1 值区域,等等)

我希望这些信息足以帮助您帮助我,但事实上,我不确定如何做到这一点,因为我做错了。请随时询问更多信息。

最佳答案

基于this answer您可以使用 scipy 库中的 ndimage 来完成此操作。我将您的数据应用于他的答案,这就是我得到的结果:

from scipy import ndimage
import numpy as np

data_tup = ((1,1,0,0,0),
(1,1,2,0,0),
(0,2,2,2,0),
(0,0,0,2,0),
(0,0,0,1,0))

data_list = [[1,1,0,0,0],
[1,1,2,0,0],
[0,2,2,2,0],
[0,0,0,2,0],
[0,0,0,1,0]]

def find_clusters(array):
clustered = np.empty_like(array)
unique_vals = np.unique(array)
cluster_count = 0
for val in unique_vals:
labelling, label_count = ndimage.label(array == val)
for k in range(1, label_count + 1):
clustered[labelling == k] = cluster_count
cluster_count += 1
return clustered, cluster_count

clusters, cluster_count = find_clusters(data_list)
clusters_tup, cluster_count_tup = find_clusters(data_tup)
print(" With list of lists, Found {} clusters:".format(cluster_count))
print(clusters, '\n')

print(" With tuples of tuple, Found {} clusters:".format(cluster_count_tup))
print(clusters_tup)

Output:

With list of lists, Found 5 clusters:
[[2 2 0 0 0]
[2 2 4 0 0]
[1 4 4 4 0]
[1 1 1 4 0]
[1 1 1 3 0]]

With tuples of tuple, Found 5 clusters:
[[2 2 0 0 0]
[2 2 4 0 0]
[1 4 4 4 0]
[1 1 1 4 0]
[1 1 1 3 0]]

两次输出都是列表的列表。如果您希望有不同的功能,则需要更改内部功能。

关于python - 如何重写一个列表列表,使 "islands"个值彼此唯一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71980880/

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