首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Matlab中确定containers.Map中是否存在子键

如何在Matlab中确定containers.Map中是否存在子键
EN

Stack Overflow用户
提问于 2017-06-10 19:08:24
回答 1查看 119关注 0票数 0

我有一个带有字符数组键的containers.Map。例如:

代码语言:javascript
运行
复制
keySet =   {'1 2 4 5', '1 3 45', '1 2', '4 5'};
valueSet = [1, 2, 3, 4];
mapObj = containers.Map(keySet,valueSet)

如果我用了,

代码语言:javascript
运行
复制
isKey(mapObj,'1 2') 

结果= 1。我需要使用子密钥too.means,我需要确定子密钥是否存在于密钥中。例如isSubKey(mapObj,'1 2 5')和result是1,因为'1 2 5‘是'1 2 4 5’的子字符串。有什么地方像isSubKey吗?

注意: isSubKey(mapObj,'1 2 4 5')也是1。

EN

回答 1

Stack Overflow用户

发布于 2017-06-10 23:00:52

您可以使用函数keys来获取` get的列表。

然后,您可以使用函数strsplit将您的sub_key拆分为charcellarray

对“容器”的keys执行相同的操作。

然后,在三个嵌套的for loops中,将sub_key的标记与container键的标记进行比较。

一种可能的实现方式是:

代码语言:javascript
运行
复制
keySet =   {'1 2 4 5', '1 3 45', '1 2', '4 5'};
valueSet = [1, 2, 3, 4];
mapObj = containers.Map(keySet,valueSet)

% Get the Keys
key_list=keys(mapObj)
% Define the sub_key to be searched
sub_key='1 2'
% Split the sub_key in an cellarray of char
sub_key_c=strsplit(sub_key)
% Initialize counters
idx_f=0
n_of_match=0
cnt=0
found=[]
% Loop over the Container keys
for i=1:length(key_list)
   % Split the current key in an cellarray of char
   key_cell=strsplit(char(key_list(i)))
   % If the lenght of the searched sub_key is greater than the current
   % container key it can not a sub_key
   if(length(key_cell) < length(sub_key_c))
      continue
   end
   idx_f=0
   % Loop over the elements of the sub_key
   for j=1:length(sub_key_c)
      % Loop over the elements of the current key
      for k=1:length(key_cell)
         sub_key_c(j)
         key_cell(k)
         % If a match is found, increment the match counter and go to the
         % next sub_key element
         if(strcmp(sub_key_c(j),key_cell(k)))
            if(idx_f ~= k)
               n_of_match=n_of_match+1
               idx_f=k
               break
            end
         end
      end
   end
   % If the number of matches is equal to the length of the sub_key, the
   % sub_key is actually a sub_key
   if(n_of_match == length(sub_key_c))
      cnt=cnt+1;
      found(cnt)=i
      n_of_match=0
   end
   n_of_match=0
end
% Display the results
if(~isempty(found))
   disp(['The sub_key ' sub_key ' has been found in:'])
   for i=1:length(found)
      key_list(found(i))
   end
else
   disp(['The sub_key ' sub_key ' has not been found'])
end

一些测试:

代码语言:javascript
运行
复制
sub_key='1 2'
The sub_key 1 2 has been found in:
ans = 
    '1 2'
ans = 
    '1 2 4 5'


sub_key='5 4'
The sub_key 5 4 has been found in:
ans = 
    '1 2 4 5'
ans = 
    '4 5'


sub_key='1 1'
The sub_key 1 1 has not been found
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44472638

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档