Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中,从变量中的多个项创建一个列表_Python - Fatal编程技术网

在python中,从变量中的多个项创建一个列表

在python中,从变量中的多个项创建一个列表,python,Python,我制作了一个简单的程序,可以读取一个包含3行文本的文件。我已经拆分了这些行,并从t2变量中得到了输出。如何去掉括号,使其成为一个列表 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',

我制作了一个简单的程序,可以读取一个包含3行文本的文件。我已经拆分了这些行,并从t2变量中得到了输出。如何去掉括号,使其成为一个列表

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']

可以将所有拆分的线添加到一起:

fname = 'dogD.txt'
t2=[]
with open(fname) as fh:
  for line in fh:
    t2 += line.strip().split()
  print t2
您还可以使用函数并返回在内存使用方面更高效的生成器:

fname =  'dogD.txt'
def spliter(fname):
    with open(fname) as fh:
      for line in fh:
        for i in line.strip().split():
          yield i
如果要循环结果,可以执行以下操作:

for i in spliter(fname) :
       #do stuff with i
如果要获取列表,可以使用
list
函数将生成器转换为列表:

print list(spliter(fname))

它们都是不同的列表,如果要使它们成为单个列表,应该在for循环之前定义一个列表,然后使用从文件中获得的列表扩展该列表

范例-

fname = 'dogD.txt'
fh = open(fname)
res = []
for line in fh:
    t2 = line.strip().split()
    res.extend(t2)
print res
或者也可以使用列表连接

fname = 'dogD.txt'
fh = open(fname)
res = []
for line in fh:
    t2 = line.strip().split()
    res += t2
print res

使用extend()方法可以轻松完成:


操作符
模块定义了
+
操作符的函数版本;可以添加列表-这是串联

fname = 'dogD.txt'
fh = open(fname)
res = []
for line in fh:
    t2 = line.strip().split()
    res += t2
print res
下面的方法打开文件并通过剥离/拆分来处理每一行。然后将单独处理的行连接到一个列表中:

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))

谢谢你的帮助,卡斯拉,非常感谢appreciated@PeterP不客气!如果有帮助,你可以通过回答告诉社区!;)请记住接受一个对你帮助最大(或你最喜欢)的答案。