首页 > 技术文章 > python与C,在写程序时踩过的坑!

ruili07 2018-09-27 18:23 原文

1.  python与C有很多相似之处, 其一就是指针的大量应用,  因此在使用临时变量保存数据, 并将临时变量传递给其他变量时需要创建内存;

     例如,在C中, char *temp 每次获取到不同的字符串, 依次放入 char **list中,    先申请一块内存  char *f = malloc(sizeof(char)*10);  f=temp; *list = f;    这样temp在改变时, 就不会影响到list; 下一个 *(list+1)=..

     python中使用复制申请内存,   save_temp = temp.copy(),  但是在向list集合中存储时, 不需要手动创建内存, 会自动创建; 

 

2. 一个列表中, 循环删除预定位置的元素, 在使用双重for时会造成指针移位, 因此可使用先复制list, 遍历复制的list,  for i in copy_list:   然后在需要删除的列表 remove(i), 使用复制列表固定指针;

   另一种做法是:     while(len(temp_list)>0):  i = list[0]  list.remove(i), 使用常量0 固定指针;

 

3. C中读取每行数据:

先在函数参数中定义字符串指针 存储行数据 read_line(File *fp, char *word),当然在函数内定义数组也可以但是相比比较耗内存,  然后为每个位置赋值;

*word = '\0';

char var = fgetc(fp);

while(var != EOF && var != '\n'){

  *(word++) = var;    //为当前位置赋值

  *word = '\0'           //为下一个位置赋值, 避免无法读取内存

  var = fgetc(fp);

 

4. C中对每行数据, 按符号进行切分, 例如每行数据按 ;切割

split_seq(char *line,char **f):

char temp[30];      //存储临时数据

size_t i;                //记录字符地址长度

char *copy;          //创建新空间 

while(strlen(line)>0){

  char *p = strchr(line, ';');       //找到分隔符位置

  size_t  sub_len = strlen(line) - strlen(p);    //计算需要切割的长度

  for(int i=0; i<sub_len; i++){

    temp[i] = line[i];

  }

  temp[i] = '\0';             //将数据填充进temp

  copy = malloc(sizeof(char)*10);   //创建内存,固化数据

  strcpy(copy, temp);

  *f = copy;

  line = p+1;     //移动line的指针

  if (*line == '|') break;

  f = f+1;         //如果不是结尾, 则增加指针;

  memset(temp, 0, sizeof(temp));           //相当于clear 数组;

}

 

 5. C中找到目标key值:

 char temp[30];    //key最长30
 int targe_len = strlen(targe);
 
 bool flag = false;
 while (!flag)
 {
  char *p = strchr(line, targe[0]);    //找到目标字符串的开头位置, *p 是在line的地址
  if (!p) return flag;
  
  int i;
  for (i = 0; i < targe_len; i++) {
   temp[i] = p[i];
   //*(temp + i) = *(p + 1);
  }
  flag = strcmp(temp, targe);         //是否能找到目标字符串, key值,  在这里判断的原因在于 加上'\0'后, 就无法判断字符串相等;
  temp[i] = '\0';   
}

 

 

6. python字典的一些用法:  初始化字典的一个技巧-> indict_init = lammda:{'conv_w':None, 'conv_b':None}      conv_bn = indict_init()即可完成初始化  conv_bn[...]赋值

    判断字典中是否有该key,   if conv_bn.get(...),  判断value是否为空 if conv_bn[...] is None,

    对字典排序  sorted(dict.keys())     或者 sorted(dict.items())

 

7. 将矩阵展开为一维集合 [ i for line in matrix for i in line ] ,   对矩阵各列排序  sorted(param_matrix, key=lambda params:[params[3],params[1]],reverse=True),

    将map的用法:   min([i[0] for i in list(map(lambda x: (x[1],x[3]), params)) if i[1]<height])

    将多个list组成一个矩阵  np.c_[all_index, length, width, height, priority, price]

 

8. 使用pandas做文本操作:  data_set = pd.read_excel(path)

# 清洗尺寸中的空值项
null_num = data_set['尺寸'].isnull().value_counts()

data_set['尺寸'].apply(lambda x: np.NAN(x) if str(x).isspace() else x)
data_set['尺寸'].fillna(143)
null_index = data_set[(data_set['尺寸'] == 143)].index.tolist()
data_set = data_set.drop(null_index, axis=0)

# 拆分尺寸
loc = data_set['尺寸']
loc = loc.tolist()






















 

推荐阅读