python二维数组上的一些操作
发布日期:2021-09-30 09:33:28 浏览次数:22 分类:技术文章

本文共 1246 字,大约阅读时间需要 4 分钟。

# -*- coding: utf-8 -*-
#读取文件内容,生成二维数组    
def generate_list2array(filepath):
    f = open(filepath,'r')
    i = 1
    t = f.readlines()
    total_rows = len(t)
    f.close()
    
    f = open(filepath,'r')
    list2array=[]
    while i<=total_rows:
        s = f.readline()
        slist = s.split() #字符串的split函数默认分隔符是空格 ' '
        list2array.append(slist) 
        i=i+1
    f.close()
    return list2array
#二维数组转置
def trans_list2array(list2array):
    rows = len(list2array)
    columns = len(list2array[0]) 
    t_list2array=[[r[col]for r in list2array] for col in xrange(columns)] 
    return t_list2array
#删除二维数组中,对应项组成的列中含有‘0’>=90%的每一行的此项
def delete_zero_columns(list2array):
    t_list2array = trans_list2array(list2array)
    t_rows = len(t_list2array)
    t_columns = len(t_list2array[0])
    not_zero_rows = []
    t_result_list = []
    #先记录per_of_zero>=0.9的行号,最后再统一删除,否则出现list index out of range错误
    for row in xrange(t_rows):
         per_of_zero = float(t_list2array[row].count('0'))/t_columns
         if per_of_zero<0.9:
             not_zero_rows.append(row)
    for row in xrange(len(not_zero_rows)):
        r = not_zero_rows[row]
        t_result_list.append(t_list2array[r])
    result_list = trans_list2array(t_result_list)
    return result_list
            
#将二维数组写回文件
def write_back(result_list , file_path):
    f = open(file_path,'w')
    f.writelines('\n'.join([' '.join(c for c in row) for row in result_list]))    
    f.close()

转载地址:https://blog.csdn.net/h_hzhou/article/details/52217063 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:python获取今天00:00:00的时间戳
下一篇:sql利用正则从字符串中抽取字段

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年04月19日 11时31分12秒