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

本文介绍了Python中使用set和sorted函数进行数据去重和排序的方法。通过示例展示了如何使用set创建无序且不重复的集合,以及如何使用sorted对列表进行排序,包括正序和反序。同时,提到了sort和sorted的区别,并提供了一个统计英文文章中高频词的实现案例。
部署运行你感兴趣的模型镜像

前言

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

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 # fromtuple8 print(set(('a', 'e', 'i', 'o', 'u')))9

10 # fromlist11 print(set(['g', 'o', 'o', 'g', 'l', 'e']))

12

13 # fromrange14 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))

#stringpyString= '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:反向排序

# setpySet= {'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))

# frozensetpyFSet= 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 forsort2 def takeSecond(elem):3 return elem[1]4

5 # random list6 random = [(2, 2), (3, 4), (4, 1), (1, 3)]7

8 # sort list with key9 sortedList = sorted(random, key=takeSecond)10

11 # print list12 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 repeat10 words = set(lst)11 d ={}12 for word inwords: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 returnresult[:num]20

21 def test():22 topWords = findTopFreqWords('test.txt',10)23 print topWords24

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,

您可能感兴趣的与本文相关的镜像

Python3.11

Python3.11

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值