python中sorted()和set()去重,排序

时间:2021-02-11 07:35:28

前言

在看一个聊天机器人的神经网络模型训练前准备训练数据,需要对训练材料做处理(转化成张量)需要先提炼词干,然后对词干做去重和排序

words = sorted(list(set(words)))

对这三个方法做一下整理:

1.set()

语法:set([iterable])

参数:可迭代对象(可选),a sequence (string, tuple, etc.) or collection (list, set, dictionary, etc.) or an iterator object to be converted into a set

返回值:set集合

作用:去重,因为set集合的本质是无序,不重复的集合。所以转变为set集合的过程就是去重的过程

 # empty set
print(set()) # from string
print(set('google')) # from tuple
print(set(('a', 'e', 'i', 'o', 'u'))) # from list
print(set(['g', 'o', 'o', 'g', 'l', 'e'])) # from range print(set(range()))

运行结果:

set()
{'o', 'G', 'l', 'e', 'g'}
{'a', 'o', 'e', 'u', 'i'}
{'e', 'g', 'l', 'o'}
{, , , , }

2.sorted()

语法:sorted(iterable[, key][, reverse])

参数:

iterable 可迭代对象,- sequence (string, tuple, list) or collection (set, dictionary, frozen set) or any iterator

reverse 反向(可选),If true, the sorted list is reversed (or sorted in Descending order)

key (可选),function that serves as a key for the sort comparison

返回值:a sorted list 一个排好序的列表

示例1:排序

# vowels list
pyList = ['e', 'a', 'u', 'o', 'i']
print(sorted(pyList)) # string
pyString = 'Python'
print(sorted(pyString)) # vowels tuple
pyTuple = ('e', 'a', 'u', 'o', 'i')
print(sorted(pyTuple))

结果:

['a', 'e', 'i', 'o', 'u']
['P', 'h', 'n', 'o', 't', 'y']
['a', 'e', 'i', 'o', 'u']

示例2:反向排序

# set
pySet = {'e', 'a', 'u', 'o', 'i'}
print(sorted(pySet, reverse=True)) # dictionary
pyDict = {'e': , 'a': , 'u': , 'o': , 'i': }
print(sorted(pyDict, reverse=True)) # frozen set
pyFSet = frozenset(('e', 'a', 'u', 'o', 'i'))
print(sorted(pyFSet, reverse=True))

结果:

['u', 'o', 'i', 'e', 'a']
['u', 'o', 'i', 'e', 'a']
['u', 'o', 'i', 'e', 'a']

示例3:指定key parameter排序

 # take second element for sort
def takeSecond(elem):
return elem[] # random list
random = [(, ), (, ), (, ), (, )] # sort list with key
sortedList = sorted(random, key=takeSecond) # print list
print('Sorted list:', sortedList)

结果:

Sorted list: [(, ), (, ), (, ), (, )]

值得一提的是,sort()和sorted()的区别:

sort 是应用在 list 上的方法(list.sort()),sorted 可以对所有可迭代的对象进行排序操作(sorted(iterable))。
list 的 sort 方法返回的是对已经存在的列表进行操作,无返回值,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。

在了解这几个函数的过程中,发现了一个博友的文章,关于校招题目的,摘其中一道题如下:

原文链接:http://www.cnblogs.com/klchang/p/4752441.html

用python实现统计一篇英文文章内每个单词的出现频率,并返回出现频率最高的前10个单词及其出现次数,并解答以下问题?(标点符号可忽略)

答案如下:

 def findTopFreqWords(filename, num=):
'Find Top Frequent Words:'
fp = open(filename, 'r')
text = fp.read()
fp.close() lst = re.split('[0-9\W]+', text) # create words set, no repeat
words = set(lst)
d = {}
for word in words:
d[word] = lst.count(word)
del d[''] result = []
for key, value in sorted(d.iteritems(), key=lambda (k,v): (v,k),reverse=True):
result.append((key, value))
return result[:num] def test():
topWords = findTopFreqWords('test.txt',)
print topWords if __name__=='__main__':
test()

使用的 test.txt 内容如下,

3.1   Accessing Text from the Web and from Disk

Electronic Books

A small sample of texts from Project Gutenberg appears in the NLTK corpus collection.
However, you may be interested in analyzing other texts from Project Gutenberg.
You can browse the catalog of 25,000 free online books at http://www.gutenberg.org/catalog/, and obtain a URL to an ASCII text file.
Although 90% of the texts in Project Gutenberg are in English, it includes material in over 50 other languages, including Catalan, Chinese, Dutch, Finnish, French, German, Italian,