提问者:小点点

将list插入set后,set只包含list中的项目,而不包含list中的项目


我正在学习Python,无意中发现了下面的activity。 我试图从列表列表中筛选出唯一项,并尝试了以下操作:

数据:sent_list=[['cleverness','wit'],['the','best','story'],['best','story'],['wit']]

我试过:

word_set = set()
for sent in sent_list:
    for word in sent:
        word_set.update(word)

word_set

产出为:

{'b', 'c', 'e', 'h', 'i', 'l', 'n', 'o', 'r', 's', 't', 'v', 'w', 'y'}

但预期的代码和结果是:

word_set = set()
for sent in sent_list:
    word_set.update(sent)
word_set

{'best', 'cleverness', 'story', 'the', 'wit'}

我使用第一个“for”循环来访问主列表中的每个子列表,然后使用第二个“for”循环来访问子列表中的每个单词,但似乎我的理解是错误的。 还有,在正确的代码中,如果一个list直接更新为set,set应该有list在里面,不是吗? 请帮助我理解这个概念。


共1个答案

匿名用户

此处使用的正确方法是Set.Add(word)而不是Set.Update(word)。