python二維陣列上的一些操作
阿新 • • 發佈:2019-02-08
# -*- 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()
#讀取檔案內容,生成二維陣列
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()