Python合并函数翻译成Matlab无法正常工作

时间:2017-03-21 21:54:17

标签: python matlab merge

对于以下很好用的Python代码

#--------------------------------------------------
s = [[1,2,3],[3,6],[9,0],[0,8]]
s = [set(i) for i in s if i]
t = []
while len(t) != len(s):
    t = s
    s = []
    for i in range(len(t)):
        for j in range(len(s)):
            if not s[j].isdisjoint(t[i]):
                s[j] = s[j].union(t[i])
                break
        else: s.append(t[i])
print(s)
#--------------------------------------------------
>>> [{1, 2, 3, 6}, {0, 9, 8}]
#--------------------------------------------------

我对Matlab的翻译为:

%--------------------------------------------------
s = {[1,2,3],[3,6],[9,0],[0,8]};
t = {};
while length(t) ~= length(s)
    t = s;
    s = {};
    for i=1:length(t)
        for j=1:length(s)
            if ~isempty(intersect(s{j},t{i}))
                s{j} = union(s{j},t{i});
                break
            else
                s = [s; t{i}];
            end
        end
        if isempty(s); s = [s; t{i}]; end
    end
end
s{:}
%--------------------------------------------------
ans =
     1     2     3     6
ans =
     0     8     9
ans =
     0     8
%--------------------------------------------------

工作不正确!

问:是什么导致这种情况?

参考文献: Python: simple list merging based on intersections
agf

之后的Python代码

1 个答案:

答案 0 :(得分:1)

好吧,我可以找到如下解决方案。

%--------------------------------------------------
s = {[1,2,3],[3,6],[9,0],[0,8]};
t = {};
while length(t) ~= length(s)
    t = s;
    s = {};
    for i=1:length(t)
        for j=1:length(s)
            if ~isempty(intersect(s{j},t{i}))
                s{j} = union(s{j},t{i});
                j = 0;
                break;
            end
        end
        if isempty(s) || (j == length(s));
            s = [s; t{i}];
        end
    end
end
s{:}
%--------------------------------------------------
ans =
     1     2     3     6
ans =
     0     8     9

其中j = 0;if isempty(s) || (j == length(s));在Python版本中符合else: