Home>Article>Backend Development> Python reads multiple lines of data
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__=='__main__': inData = get2DimData() print inData print '\n' 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!