Home  >  Article  >  Backend Development  >  Python reads multiple lines of data

Python reads multiple lines of data

不言
不言Original
2018-04-19 10:38:326734browse

The following is an example of reading multiple rows of data in python. It has a good reference value and I hope it will be helpful to everyone. Let’s take a look together

1. Preface

This article mainly uses python’s raw_input() function to read in multiple lines of variable-length data. The sign of the end of input is to press Enter without entering a number, and fill in the specific number as a two-dimensional matrix

2. Code

def get2DlistData():
 res = []
 
 inputLine = raw_input() #以字符串的形式读入一行
 #如果不为空字符串作后续读入
 while inputLine != '': 
  listLine = inputLine.split(' ') #以空格划分就是序列的形式了
  listLine = [int(e) for e in listLine ] #将序列里的数由字符串变为int类型
  res.append( listLine )
  
  inputLine = raw_input()
 
 return res
 
def get2DMatData( inList , val ):
 ''' 
 输入:inList为不等长的二维数组,val为需填充的值
 输出:np.array的形式输出填补完的二维矩阵
 '''
 maxCols = 0
 #获得最大长度的子序列
 for i in range( len( inList ) ):
  lenI = len( inList[i] )
  if lenI > maxCols:
   maxCols= lenI
 #对每个子序列作填充   
 for i in range( len( inList ) ):
  num = len( inList[i] )
  while(num <= maxCols):
   inList[i].append( val )
   num += 1
 
 return np.array( inList , dtype = np.int64 ) 
if __name__==&#39;__main__&#39;:
 inData = get2DimData()
 print inData
 print &#39;\n&#39;
 
 matArray = get2DMatData(inData , 0)
   
 print( matArray )

3. Running results

##Related recommendations:

Simple use of python reading files and time/sys module

The above is the detailed content of Python reads multiple lines of data. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn