新浪博客

数据结构(三)

2023-05-17 11:46阅读:
2)推导式
现在我们来看数据结构中的推导式(List comprehension),也许你还看到过它的另一种名称叫做列表的解析式,在这里你只需要知道这两个说的真实是一个东西就可以了
现在我有10个元素要装进列表中,普通的写法是这样的:
a = []
for i in range(1,11):
a.append(i)


print(a)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

下面换成列表解析的方式来写:
b = [ i for i in range(1,11)]
print(b)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

列表解析式不仅非常方便,并且在执行效率上要远远胜过前者
,我们把两种不同的列表操作方式所耗费的时间进行对比,就不难发现其效率的巨大差异:
import time
a = []
t0 = time.process_time_ns()
for i in range(1,2000000):
a.append(i)


print(time.process_time_ns() - t0,' nanoseconds process time of a')
1078125000 nanoseconds process time of a

t0 = time.process_time_ns()
b = [i for i in range(1,2000000)]
print(time.process_time_ns() - t0,' nanoseconds process time of b')
109375000 nanoseconds process time of b

列表推导式的用法也很好理解,可以简单地看成两部分红色虚线后面的是我们熟悉的for循环的表达式,而虚线前面的可以认为是我们想要放在列表中的元素,在这个例子中放在列表中的元素即是后面循环的元素本身 数据结构(三)
为了更好地理解这句话我们继续看几个例子:
a = [i**2 for i in range(1,10)]
a
[1, 4, 9, 16, 25, 36, 49, 64, 81]
c = [j+1 for j in range(1,10)]
print(c)
[2, 3, 4, 5, 6, 7, 8, 9, 10]
k = [n for n in range(1,10) if n % 2 ==0]
print(k)
[2, 4, 6, 8]
z = [letter.lower() for letter in 'ABCDEFGHIGKLMN']
print(z)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'g', 'k', 'l', 'm', 'n']

字典推导式的方式略有不同,主要是因为创建字典必须满足键—值的两个条件才能达成:
d = {i:i+1 for i in range(4)}
print(d)
{0: 1, 1: 2, 2: 3, 3: 4}
g = {i:j for i,j in zip(range(1,6),'abcde')}
print(g)
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
h = {i:j.upper() for i,j in zip(range(1,6),'abcde')}
print(h)
{1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E'}

3)循环列表时获取元素的索引
现在我们有一个字母表如何能像图中一样在索引的时候得到每个元素的具体位置的展示呢?
前面提到过,列表是有序的,这时候我们可以使用Python中独有的函数enumerate来进行:
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
for num,letter in enumerate(letters):
print(letter,'is',num + 1)

a is 1
b is 2
c is 3
d is 4
e is 5
f is 6
g is 7

4)综合项目
在做项目之前还是提前做一些准备,学习一些必要的知识现在我们使用split方法将字符串中的每个单词分开,得到独立的单词:
lyric = 'The night begin to shine, the night begin to shine'
words = lyric.split()
print(words)
['The', 'night', 'begin', 'to', 'shine,', 'the', 'night', 'begin', 'to', 'shine']

接下来是词频统计我们使用count方法来统计重复出现的单词:
path = '/Users/Hou/Desktop/Wald n.txt'
with open(path,'r') as text: words = text.read().split() print(words)
for word in words:
print('{}-{} times'.format(word,words.count(word)))

结果出来了,但是总感觉有一些奇怪,仔细观察得出结论:
1.有一些带标点符号的单词被单独统计了次数;
2.有些单词不止一次地展示了出现的次数;
3.由于Python对大小写敏感,开头大写的单词被单独统计了
现在我们根据这些点调整一下我们的统计方法,对单词做一些预处理:
1.import string
2.path = '/Users/Hou/Desktop/Walden.txt'

3.with open(path,'r') as text:
4. words = [raw_word.strip(string.punctuation).lower() for raw_word in text.read().split()]
5. words_index = set(words)
6. counts_dict = {index:words.count(index) for index in words_index}

7.for word in sorted(counts_dict,key=lambda x: counts_dict[x],reverse=True):
8. print('{} -- {} times'.format(word,counts_dict[word]))

1:引入了一个新的模块string其实这个模块的用法很简单,我门可以试着把string.punctuation打印出来,其实这里面也仅仅是包含了所有的标点符号——!#$%&(),./:;<=>?@[\](|}
4:在文字的首位去掉了连在一起的标点符号,并把首字母大写的单词转化成小写;
5:将列表用set函数转换成集合,自动去除掉了其中所有重复的元素;
6:创建了一个以单词为键(key)出现频率为值(value)的字典;
78:打印整理后的函数,其中key=lambda x:counts_dict[x]叫做lambda表达式,可以暂且理解为以字典中的值为排序的参数
说明:程序中名为“Walden.txt”的文件,可点击下面的网址下载(https://pan.baidu.com/s/1o75GKZ4)。

我的更多文章

下载客户端阅读体验更佳

APP专享