转换为Matlab的Python合并功能不起作用 [英] Python merge function translated into Matlab not working
本文介绍了转换为Matlab的Python合并功能不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于以下运行良好的Python代码
For the following nicely working Python code
#--------------------------------------------------
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的翻译为:
My translation to Matlab as:
%--------------------------------------------------
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
%--------------------------------------------------
工作不正常!
问:是什么原因造成的?
Refs:
Python: simple list merging based on intersections
Python code after agf
推荐答案
好吧,我可以找到如下解决方案.
Well, I could find a solution as follows.
%--------------------------------------------------
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));
满足else:
的要求,如Python版本一样.
where j = 0;
and if isempty(s) || (j == length(s));
satisfy else:
as in the Python version.
这篇关于转换为Matlab的Python合并功能不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文