make one list from multi items in a variable in python
我制作了一个简单的程序,它读取一个由3行文本组成的文件。我已经拆分了这些行,并从t2变量中得到输出。如何去掉括号使其成为一个列表?
1 2 3 4 5 6 7 8 9 10 | fname = 'dogD.txt' fh = open(fname) for line in fh: t2 = line.strip() t2 = t2.split() print t2 ['Here', 'is', 'a', 'big', 'brown', 'dog'] ['It', 'is', 'the', 'brownest', 'dog', 'you', 'have', 'ever', 'seen'] ['Always', 'wanting', 'to', 'run', 'around', 'the', 'yard'] |
使用extend()方法很容易做到:
1 2 3 4 5 6 | fname = 'dogD.txt' fh = open(fname) t2 = [] for line in fh: t2.append(line.strip().split()) print t2 |
它们都是不同的列表,如果要使它们成为单个列表,应在for循环之前定义一个列表,然后使用从文件中获得的列表扩展该列表。
示例-
1 2 3 4 5 6 7 | fname = 'dogD.txt' fh = open(fname) res = [] for line in fh: t2 = line.strip().split() res.extend(t2) print res |
也可以使用列表串联。
1 2 3 4 5 6 7 | fname = 'dogD.txt' fh = open(fname) res = [] for line in fh: t2 = line.strip().split() res += t2 print res |
您可以将所有拆分的行添加到一起:
1 2 3 4 5 6 | fname = 'dogD.txt' t2=[] with open(fname) as fh: for line in fh: t2 += line.strip().split() print t2 |
您还可以使用函数并返回在内存使用方面效率更高的生成器:
1 2 3 4 5 6 | fname = 'dogD.txt' def spliter(fname): with open(fname) as fh: for line in fh: for i in line.strip().split(): yield i |
如果要循环结果,可以执行以下操作:
1 2 | for i in spliter(fname) : #do stuff with i |
如果您想得到一个列表,可以使用
1 | print list(spliter(fname)) |
下面的方法打开文件并通过剥离/拆分处理每一行。然后将单独处理的行连接到一个列表中:
1 2 3 4 5 6 7 8 9 10 | import operator # determine what to do for each line in the file def procLine(line): return line.strip().split() with open("dogD.txt") as fd: # a file is iterable so map() can be used to # call a function on each element - a line in the file t2 = reduce(operator.add, map(procLine, fd)) |