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

前言

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

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集合的过程就是去重的过程

 1 # empty set
 2 print(set())
 3 
 4 # from string
 5 print(set('google'))
 6 
 7 # from tuple
 8 print(set(('a', 'e', 'i', 'o', 'u')))
 9 
10 # from list
11 print(set(['g', 'o', 'o', 'g', 'l', 'e'])) 
12
13 # from range 14 print(set(range(5)))

运行结果:

set()
{'o', 'G', 'l', 'e', 'g'}
{'a', 'o', 'e', 'u', 'i'}
{'e', 'g', 'l', 'o'}
{0, 1, 2, 3, 4}

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': 1, 'a': 2, 'u': 3, 'o': 4, 'i': 5}
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排序

 1 # take second element for sort
 2 def takeSecond(elem):
 3     return elem[1]
 4 
 5 # random list
 6 random = [(2, 2), (3, 4), (4, 1), (1, 3)]
 7 
 8 # sort list with key
 9 sortedList = sorted(random, key=takeSecond)
10 
11 # print list
12 print('Sorted list:', sortedList)

结果:

Sorted list: [(4, 1), (2, 2), (1, 3), (3, 4)]

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

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

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

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

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

答案如下:

 1 def findTopFreqWords(filename, num=1):
 2     'Find Top Frequent Words:'
 3     fp = open(filename, 'r')
 4     text = fp.read()
 5     fp.close()
 6 
 7     lst = re.split('[0-9\W]+', text)
 8 
 9     # create words set, no repeat
10     words = set(lst)
11     d = {}
12     for word in words:
13         d[word] = lst.count(word)
14     del d['']
15     
16     result = []
17     for key, value in sorted(d.iteritems(), key=lambda (k,v): (v,k),reverse=True):
18         result.append((key, value))
19     return result[:num]
20 
21 def test():
22     topWords = findTopFreqWords('test.txt',10)
23     print topWords
24 
25 if __name__=='__main__':
26     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,

  

猜你喜欢

转载自www.cnblogs.com/sen-c7/p/10414427.html
今日推荐