python之从文件读取数据到list的实例讲解
背景:
文件内容每一行是由N个单一数字组成的,每个数字之间由制表符区分,比如:
0 4 3 1 2
2 1 0 3
1 2 0
……
现在需要将每一行数据存为一个list,然后所有行组成一个大的list
工具:
1.strip():用于移除字符串头尾指定的字符,默认为空格,返回是字符串
2.split():通过指定分隔符对字符串进行切片,返回是字符串组成的list
实例:
#!/usr/bin/python #coding=utf-8 def readfile(filename): with open(filename,'r') as f: for line in f.readlines(): linestr = line.strip() print linestr linestrlist = linestr.split("\t") print linestrlist linelist = map(int,linestrlist)# 方法一 # linelist = [int(i) for i in linestrlist] # 方法二 print linelist
相关推荐
xiesheng 2020-08-02
xiaoseyihe 2020-11-16
xiaoseyihe 2020-11-16
世事一场大梦 2020-10-18
jling 2020-10-14
chenyuping 2020-10-06
kyelu 2020-08-03
KAIrving 2020-08-02
liushall 2020-07-18
shenwenjie 2020-07-07
yunfenglee 2020-07-08
83520298 2020-07-06
Jonderwu 2020-07-05
xiaobater 2020-07-04
范范 2020-06-28