【问题标题】:Creating a function that takes a list of words, and return a set of words in the sentence创建一个接受单词列表的函数,并返回句子中的一组单词
【发布时间】:2020-07-31 21:23:01
【问题描述】:
  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))

【问题讨论】:

  • 如果你使用append而不是add呢?
  • 使用update 代替add 并返回dickens_words

标签: python string list set


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    问题是 add() 只接受一个元素。

    尝试在创建集合时添加链接

    dickens_words = 集合(单词)

    【讨论】:

      【解决方案3】:

      A = list(input("statement:").strip().split(' '))

      打印(' '.join(list(dict.fromkeys(A))))

      【讨论】:

      • 嗨 Meysam,欢迎来到 SO。请使用代码格式并为您的答案提供一些上下文,通常不鼓励单独发布代码。
      猜你喜欢
      • 2022-01-01
      • 1970-01-01
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-09
      相关资源
      最近更新 更多