首页 > 解决方案 > 创建一个接受单词列表的函数,并返回句子中的一组单词

问题描述

  1. 需要创建一个接受字符串的函数

例如“你好,今天天气很好,很热”

  1. 该函数需要使用字符串中单词的 LIST,并创建一个由字符串中的单词组成的 SET。

输出应该是: ("hello" "it" "is" "a" "nice" "day" "today" "and" "hot") 注意:该集合只有句子中的唯一单词,没有重复的单词

我自己试过了,但它说错了:

opening_line="It was the best of times, it was the worst of times"

def get_vocabulary(word_list):

  words = word_list.split()

  dickens_words = set()
  dickens_words.add(words)

  return words

print(get_vocabulary(opening_line))

标签: pythonstringlistset

解决方案


您将整个列表作为单个元素添加到集合中。相反,您可以从列表中构造一个集合,它将所有单词单独添加到集合中:

def get_vocabulary(word_list):
    return set(word_list.split())

推荐阅读