当我将数据集导入数组时,每个元素的长度显示为 1

When I import a data set into an array, the length of each element appears as 1

我正在制作一个程序,将一长串单词从 .txt 文件导入到一个名为 wordlist 的数组中。然后我想根据单词的长度将它们分类。但是由于某些原因,当单词存储在数组中时,每个单词的长度显示为1。

这是代码

wordlist = []
with open('words.txt', 'r') as words:
    for line in words:
        strplines = line.strip()
        list = strplines.split()
        wordlist.append(list)
        loading = loading + 1
        print(loading,'/ 113809 words loaded')

如果我再做这样的事情

print(len(wordlist[15000]))

尽管该单词实际上有 6 个字符长,但输出为 1。 我在另一个程序中尝试过这个,但唯一的区别是我手动将一些元素输入到数组中并且它起作用了。这意味着我从 .txt 文件中删除行的方式可能存在问题。

所以单词列表是数组的数组?如果是这样,当你检查它的元素的 len 时,它会 return 这个数组中的元素数量所以 1。但是如果你做类似

len(wordlist[1500][0])

您将获得存储在数组中索引 1500 处的第一个单词的长度。

看起来您不想 append 到数组(您会添加一个列表),但您想要 extend数组。

拜托,拜托,即使内置函数不是保留字,也要避免使用它们!所以调用你的列表 lstmylist 或任何但不是 list...

代码可以变成:

wordlist = []
with open('words.txt', 'r') as words:
    for line in words:
        strplines = line.strip()
        lst = strplines.split()
        wordlist.extend(lst)
        loading = loading + 1
        print(loading,'/ 113809 words loaded')