我有一个单词列表(相当于两个完整的句子),我想把它分成两个部分:一部分包含90%的单词,另一部分包含10%的单词。在那之后,我想打印10%列表中唯一单词的列表,按顺序排序。到目前为止,这就是我所拥有的:
pos_90 = (90*len(words)) // 100 #list with 90% of the words
pos_90 = pos_90 + 1 #I incremented the number by 1 in order to use it as an index
pos_10 = (10*len(words)) // 100 #list with 10% of the words
list_90 = words[:pos_90] #Creation of the 90% list
list_10 = words[pos_10:] #Creation of the 10% list
uniq_10 = set(list_10) #List of unique words out of the 10% list
split_10 = uniq_10.split()
sorted_10 = split_10.sort()
print(sorted_10)我收到一个错误,说明split不能应用于set,所以我假设我的错误一定是在最后一行代码中。知道我在这里错过了什么吗?
发布于 2018-10-30 18:49:37
split只有在从一个长str转换为所述str组件的list时才有意义。如果输入是以'word1 word2 word3'形式出现的,是的,split会将该str转换为['word1', 'word2', 'word3'],但是您的输入是一个set,并且没有像您想要的那样“拆分”set的明智方法;它已经是一袋分离的项目了。
您真正需要做的就是将您的set转换回排序的list。取代:
split_10 = uniq_10.split()
sorted_10 = split_10.sort()有以下两种:
sorted_10 = list(uniq_10)
sorted_10.sort() # NEVER assign the result of .sort(); it's always going to be None或者包含语言化和排序的更简单的一行:
sorted_10 = sorted(uniq_10) # sorted, unlike list.sort, returns a new list最后一个选项通常是将任意迭代转换为list并排序新的list并返回结果的最Pythonic方法。它不改变输入,不依赖于输入是特定类型(set、tuple、list,没关系),而且启动更简单。只有在已有已知的list.sort()时才使用list,并且不介意对其进行变异。
https://stackoverflow.com/questions/53070941
复制相似问题