2017-06-17 186 views
0

我正在读取.csv中的数据。一列代表发生事件的格式周:从字符串读取数据并区分元素是数字还是数组

1,2,5,6,7,8,10

1-2,5-8,10

,有时甚至像1-2,5,6,7,8,10一个奇怪的混合方式。

的最小周数是单int值(如'1'),最大是从来没有超过两位数int(如'24'),因为有52个星期一年更大。

第二障碍','作为数组的元素。所以我必须从逗号中清除字符串,并将其首先拆分为(','),然后处理主要问题。

问题:

没有人有一个很好的解决方案如何区分在索引的元素是否为范围或单周,并且如果元素是一个数组与尽可能多的元件,只要该范围为,代替它例如:

[1,3-5,7]应该成为[1,3,4,5,7]

我的尝试:

现在我所能想到的最好的方法就是简单计算索引元素的长度,如果它大于2比我假设元素是一个范围,并将它拆分为'-'。然后将每个元素(如果不是数组)复制到一个新的数组中,或者在for loop中追加带有范围元素的新数组。

回答

1

这可能会更有意义的检查项目中-的存在。这里是我的版本:

for item in array: 
    if '-' in item: 
     item_split = list(map(int, item.split('-'))) 
     item_list = list(range(item_split[0], item_split[1] + 1)) 
     array.extend(item_list) 

那么你就必须清理你的列表中删除所有的“范围”:

array = [i for i in array if not '-' in i] 

假设你需要的所有整数:

array = list(map(int, array)) 

然后删除重复项:

array = list(set(array)) 
+0

对不起,伙计,我忘了粘贴问题的第二部分,我刚刚添加,你的解决方案比计算元素长度更优雅。 –

+0

@StanRedoute请检查最新的答案。 – makeiteasy

0
static int[] ParseStringInt32ListToIntArray(string IntegerList) 
     { 
      int[] ret; 
      bool contains = (IntegerList.Contains("[") == true || IntegerList.Contains(",")==true); 

      if (!contains) 
       return ret = new int[1] { Int32.Parse(IntegerList) }; 

       IntegerList = IntegerList.Replace("-","[").Replace("[", "").Replace("]", ""); 
       var split = IntegerList.Split(','); 
       ret = new int[IntegerList.Split(',').Length]; 
       for(int i = 0;i< split.Length;i++) 
       { 
        ret[i] = Int32.Parse(split[i]); 
       } 

     return ret; 
    } 
+0

不是java的问题 –

相关问题