Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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_List_Readfile - Fatal编程技术网

Python 如何获取列表而不是列表的列表?

Python 如何获取列表而不是列表的列表?,python,list,readfile,Python,List,Readfile,我正在尝试读取以下格式的文本文件a b c d e f g h。我接受一个新的空列表单词=[] 我的代码是: f = open("letters.txt") word = [] for line in f: line = line.split(" ") word.append(line) print(word) 但是,它给了我一个列表,如下所示: [['a', 'b', 'c', 'd', 'e', 'f']] 但我想把它放在一个单子里 例如: 试着这样, word =

我正在尝试读取以下格式的文本文件a b c d e f g h。我接受一个新的空列表单词=[]

我的代码是:

f = open("letters.txt")

word = []

for line in f:
    line = line.split(" ")
    word.append(line)
print(word)
但是,它给了我一个列表,如下所示:

[['a', 'b', 'c', 'd', 'e', 'f']]
但我想把它放在一个单子里

例如:

试着这样,

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


您可以打印您的行

f = open("letters.txt")

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

@拉胡尔的回答是正确的。但这应该有助于您理解何时不使用append

appendx将x作为新元素添加到列表的末尾。不管x是什么,扩展都会起作用

>>> l = []
>>> l.append(1)
>>> l.append('a')
>>> l.append({1,2,3})
>>> l.append([1,2,3])
>>> l
[1, 'a', set([1, 2, 3]), [1, 2, 3]]
>>> 
>>> 
>>> l = []
>>> l.extend(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> l.extend([1])
>>> l.extend([4,5,6])
>>> l
[1, 4, 5, 6]

您应该知道代码每行的每个变量中都有哪些数据。如果你不知道-打印出来,然后你就会知道

这次我会帮你做的

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

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

import itertools
a = [["a","b"], ["c"]]
print list(itertools.chain.from_iterable(a))
返回一个列表

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

此列表作为一个整体附加在word的末尾。这就是为什么你会得到一个列表

word [
    [ result of split of first line ]
    [ result of split of second line ]
    [ result of split of third line ]
    [ ... ]
]
如果要添加列表的每个元素,而不是将列表作为一个整体附加,则可以使用,即

虽然您可能希望在读取多行时,使用删除尾随换行符

a = line.rstrip().split(" ")
或者只使用None作为单词分隔符

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


对大文件不太好:@JacobVlijm OP描述了小内容。这就是为什么我建议这个解决方案。他提到了格式,我没有看到任何关于尺寸的东西。对于较小的文件,我会按你的方式处理。我相信他的意思并不是他在格式上所描述的…@RahulKP^Nope,只是第一行的单词。你可能想澄清一下你问题中有些令人困惑的术语。['a'、'b'、'c']表示您需要一个字符列表,而我很确定您需要一个单词列表。同样,由于同样的原因,列表中的单词而非单词会让人困惑。您好,请澄清。这个问题现在还不清楚。
word [
    [ result of split of first line ]
    [ result of split of second line ]
    [ result of split of third line ]
    [ ... ]
]
for line in f:
    a = line.split(" ")
    word.extend(a)
a = line.rstrip().split(" ")
a = line.split()