我如何获得列表而不是列表列表?

时间:2016-09-24 07:51:25

标签: python list readfile

我正在尝试使用以下格式"a b c d e f g h"读取文本文件。我拿了一个新的空列表word = []

我的代码是:

f = open("letters.txt")

word = []

for line in f:
    line = line.split(" ")
    word.append(line)
print(word)

然而,它给了我一个这样的列表列表:

[['a', 'b', 'c', 'd', 'e', 'f']]

但我想把它放在一个列表中呢?

例如:

['a', 'b', 'c']

6 个答案:

答案 0 :(得分:0)

试试这个,

word = open("letters.txt").read().split()

<强>结果

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

答案 1 :(得分:0)

您可以改为打印您的行。

f = open("letters.txt")

for line in f:
    line = line.split(" ")
print line

答案 2 :(得分:0)

@ Rahul的回答是正确的。但这应该有助于您了解何时不使用append

append(x)将x添加为列表末尾的新元素。 <{1}} x的作用并不重要。

extend

答案 3 :(得分:0)

您应该知道每行代码中每个变量中的数据。如果您不知道 - 打印它然后您就会知道。

这次我会帮你的;)

f = open("letters.txt")
# f is an open file object. BTW, you never close it.
# Consider: with open("letters.txt", "rt") as f:

word = []
# 'word' is a list. That is strange, why not 'words = []'?

for line in f:
    # 'line' is a string. Fine.

    line = line.split(" ")

    # 'line' is no longer a string. Not fine.
    # This is perfectly valid code, but bad practice.
    # Don't change the type of data stored in a variable,
    # or you'll run into problems understanding what your code does.
    # Make a new variable, if you need one, e.g. 'line_words'.

    # Anyway, 'line' is now a list of words. Whatever.

    word.append(line)

    # This added a list (line) into another list (word).
    # Now it is a list of lists. There is your error.
    # 'word += line' would do what you wanted.

所有在一起:

with open("letters.txt", "rt") as f:
    words = []
    for line in f:
        words += line.split()

答案 4 :(得分:0)

获得当前结果后,您可以尝试这样做:

import itertools
a = [["a","b"], ["c"]]
print list(itertools.chain.from_iterable(a))

答案 5 :(得分:0)

split返回一个列表

  

使用sep作为分隔符字符串,返回字符串中的单词列表。

此列表在word末尾附加作为整体。这就是你得到一份清单

的原因
word [
    [ result of split of first line ]
    [ result of split of second line ]
    [ result of split of third line ]
    [ ... ]
]

如果您想添加列表中的每个元素,而不是将列表作为一个整体添加,您可以使用extend,即

for line in f:
    a = line.split(" ")
    word.extend(a)

虽然您可能希望在阅读多行时删除带有rstrip的尾随换行符

a = line.rstrip().split(" ")

或仅使用None作为字词分隔符

  

如果未指定sep或为None,则应用不同的拆分算法:连续空格的运行被视为单个分隔符,如果字符串具有前导或尾随,则结果将在开头或结尾处不包含空字符串空白。因此,将空字符串或仅由空格组成的字符串拆分为无分隔符将返回[]。

a = line.split()