【问题标题】:make one list from multi items in a variable in python从python中的变量中的多项创建一个列表
【发布时间】:2015-09-24 22:11:06
【问题描述】:

我制作了一个简单的程序来读取一个包含 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']

【问题讨论】:

标签: python


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    它们都是不同的列表,如果你想让它们成为一个列表,你应该在 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
    

    【讨论】:

    • 请记住接受一个对你帮助最大(或者你最喜欢)的答案。
    【解决方案3】:

    你可以把所有的分割线加在一起:

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

    【讨论】:

    • 感谢您的帮助,非常感谢 Kasra
    • @PeterP 不客气!如果对您有帮助,您可以通过accepting 答案告诉社区! ;)
    【解决方案4】:

    operator 模块定义了+ 运算符的函数版本;可以添加列表 - 这是连接。

    下面的方法打开文件并通过剥离/拆分处理每一行。然后将单独处理的行连接到一个列表中:

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

    【讨论】:

      猜你喜欢
      • 2019-09-11
      • 2019-11-21
      • 2021-09-13
      • 1970-01-01
      • 2016-12-29
      • 1970-01-01
      • 2023-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多