【问题标题】:Read data from string and distinguish whether element is number or array从字符串中读取数据并区分元素是数字还是数组
【发布时间】:2017-06-17 21:34:05
【问题描述】:

我正在从.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 中附加一个范围元素的新数组。

【问题讨论】:

    标签: python arrays algorithm csv


    【解决方案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))
    

    【讨论】:

    • 对不起,伙计,我忘了粘贴我刚刚添加的问题的第二部分,您的解决方案比计算元素的长度更优雅。
    【解决方案2】:
    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;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-09
      • 2015-01-01
      • 1970-01-01
      相关资源
      最近更新 更多