函数返回相同的列表两次

2024-05-05 15:34:48 发布

您现在位置:Python中文网/ 问答频道 /正文

经重新检查后更新 我在下面创建了一个函数,它接收字符串列表,其中字符串是句子,每个句子都有不同数量的单词。 然后,我尝试使用item.split()将这些字符串分解为各自的单词,创建一个包含单词而不是句子的新列表。 然后我尝试打印新列表的长度

我正在传入一个名为split_list的列表,它是在这个函数之外定义的,是一个字符串列表(句子列表)

下面是我如何基于.txt文件创建split_list,该文件本身就是一个原始格式的长字符串

file = open("classic_cars.txt", "r")
split_list = []
for line in file:
    new_list = line.split(".")
    ultra_list = line.split("?")
    split_list.extend(new_list)
    split_list.extend(ultra_list)
#print(split_list)

问题是:我对文本文件进行了手动字数统计,结果显示有957个单词。然而,当我打印返回/新生成列表的长度时,它显示为1917。当我将新的_列表打印到控制台时,它会打印两次。它为什么这样做

def create_list_with_words(list):
  new_list = []
  for item in list:
     words = item.split()
     for word in words:
         new_list.append(word)
  print(new_list)
  print(len(new_list))

create_list_of_words(split_list)

Tags: 函数字符串intxt列表newforline
1条回答
网友
1楼 · 发布于 2024-05-05 15:34:48

您得到的重复项是因为您试图用两个不同的字符将同一行拆分两次

例如,考虑下面的行:

I am trying to learn python. Am I really? This is the sentence I will test.

如果我们将该行传递给for循环,它将按如下方式拆分该行:

First on . (dot)

new_list = ['I am trying to learn python', ' Am I really? This is the sentence I will test', '']

Second time on ? (Question Mark)

ultra_list = ['I am trying to learn python. Am I really', ' This is the sentence I will test.']

将这两个列表扩展到split_list,如下所示:


split_list.extend(new_list)
split_list.extend(ultra_list)

因此,最后的split_list将是:


split_list = ['I am trying to learn python', ' Am I really? This is the sentence I will test', '', 'I am trying to learn python. Am I really', ' This is the sentence I will test.']

您要传递给函数create_list_with_words的列表,该函数贯穿split_list的每个元素,并在空间上拆分每个元素。所以算错了

以下是更正的代码:


def create_list_with_words(list):
  new_list = []
  for item in list:
     words = item.split()
     for word in words:
         new_list.append(word)
  print(new_list)
  print(len(new_list))

file = open("classic_cars.txt", "r")
split_list = []
for line in file:
    line = line.replace("?", '')
    new_list = line.split(".")
    split_list.extend(new_list)

create_list_with_words(split_list)

根据需要,您可能需要在此代码中进行更多调整

注意:您的函数名为create_list_with_words,但调用名为create_list_of_words。我假设这是一个打字错误

相关问题 更多 >