python读记手册_Python魔力手册读书笔记

2ff34e647e2e3cdfd8dca593e17d9b0a.png

CH1处理字符串

输入如下代码1

2

3

4

5

6

7

8

9

10

11

12

13

14phone_number = '1386-666-0006'

hiding_number = phone_number.replace(phone_number[:9],'*'*9)

print(hiding_number)

search = '168'

num_a = '1386-168-0006'

num_b = '1681-222-0006'

print(search + ' is at ' +str(num_a.find(search)) + ' to ' + str(num_a.find(search) + len(search)) + ' of num_a')

print(search + ' is at ' +str(num_b.find(search)) + ' to ' + str(num_b.find(search) + len(search)) + ' of num_b')

print('{} a word she can get what she {} for.'.format('With','came'))

print('{preposition} a word she can get what she {verb} for'.format(preposition = 'With',verb = 'came'))

print('{0} a word she can get what she {1} for.'.format('With','came'))

city = input("write down the name of city:")

url = "http://apistore.baidu.com/microservice/weather?citypinyin={}".format(city)

print(url)

显示如下:

CH2函数

创建函数

设计求三角形斜边长的函数:1

2

3def (edge1, edge2):

return 'The right triangle side's length is {}'.format((edge1**2 + edge2**2)**(1/2))

print(computeEdge(3.0, 4.0))

显示结果

传递参数与参数类型

例如函数1

2def trapezoid_area(base_up, base_down, height):

return 1/2 * (base_up + base_down) * height

位置参数传递1trapezoid_area(1,2,3)

关键词参数传递1trapezoid_area(base_up=1, base_down=2, height=3)

也可以给参数添加默认值1trapezoid_area(base_up=1, base_down=2, height=3)

设计自己的函数

打开文件并写入的函数1

2

3

4

5

6

7

8def text_create(name, msg):

desktop_path = '/Users/Hou/Desktop/'

full_path = desktop_path + name + '.txt'

file = open(full_path,'w')

file.write(msg)

file.close()

print('Done')

text_create('hello','hello world')

过滤敏感词的函数1

2

3def text_filter(word,censored_word = 'lame',changed_word = 'Awesome'):

return word.replace(censored_word, changed_word)

text_filter('Python is lame!')

创建文件并输入名字,有敏感词则被过滤1

2

3

4def censored_text_create(name, msg):

clean_msg = text_filter(msg)

text_create(name,clean_msg)

censored_text_create('Try','lame!lame!lame!')

运算符

CH3循环与判断

一些简单的输入输出middle = 5

1 < middle < 10

输出 True

‘Hello’ == ‘Hello’

输出 True

成员运算符与身份运算符

创建列表1album = ['Black Star', 'David Bowie',25, True]

使用append向列表尾部添加元素1album.append('new song')

打印列表中第一个和最后一个元素1print(album[0], album[-1])

Membership Operator

关键字in not in1'Black Star' in album

测试字符串Black Star是否在列表album中,如果存在就会显示True,不存在就会显示False

Identify Operator

关键字is is not1

2name = 'hello'

'hello' is name

条件控制

循环

for循环1

2for num in range(1,11):

print(str(num) + ' + 1 =', num+1 )

输出1 + 1 = 2

2 + 1 = 3

3 + 1 = 4

4 + 1 = 5

5 + 1 = 6

6 + 1 = 7

7 + 1 = 8

8 + 1 = 9

9 + 1 = 10

10 + 1 = 11

打印九九表1

2

3for i in range(1,10):

for j in range(1,10):

print('{} X {} = {}'.format(i,j,i*j))

while循环1

2while 1 < 3:

print('这是while循环')

练习题1

2

3

4

5

6

7

8

9##### 创建10个文本 ######def

def text_creation():

path = 'G:Python_CodeTest '

for name in range(1,11):

with open(path + str(name) + '.txt', 'w') as text:

text.write(str(name))

text.close()

print('Done')

text_creation()

输出结果1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40####### 一个掷色子的小游戏 #######

import random

###摇色子的函数,返回储存三个点数结果的列表

def roll_dice(numbers=3, points=None):

print('<<<<< ROLL THE DICE! >>>>>')

if points is None:

points = []

while numbers > 0:

point = random.randrange(1,7)

points.append(point)

numbers = numbers - 1

return points

###定义Big和Small

def roll_result(total):

isBig = 11 <= total <= 18

isSmall = 3 <= total <= 10

if isBig:

return 'Big'

elif isSmall:

return 'Small'

####游戏开始

def start_game():

print('<<<<< GAME STARTS! >>>>>')

choices = ['Big', 'Small']

your_choice = input('Big or Small:')

if your_choice in choices:

points = roll_dice()

total = sum(points)

youWin = your_choice == roll_dice(total)

if youWin:

print('The points are', points, 'You win!')

else:

print('The points are', points, 'You lose!')

else:

print('Invalid Words')

start_game()

start_game()

输出结果<<<<< GAME STARTS! >>>>>

Big or Small:Big

<<<<< ROLL THE DICE! >>>>>

<<<<< ROLL THE DICE! >>>>>

The points are [2, 3, 1] You lose!

CH4 数据结构

列表1list = [val1, val2, val3, val4]

字典1dict = {key1:val1, key2:val2}

元组1tuple = (val1, val2, val3, val4)

集合1set = {val1, val2, vla3, val4}

列表(list)列表中的每一个元素都是可变的

列表中的元素是有序的,也就是说每一个元素都有一个位置

列表可以容纳Python中的任何对象1list = ['pineapple', 'pear']

insert()1list.insert(1, 'grape')

输出[‘pineapple’, ‘grape’, ‘pear’]

在使用insert方法的时候,必须指定在列表中要插入新的元素的位置,插入元素的实际位置是在指定位置元素之前的位置,如果指定插入的位置在列表中不存在,实际上也就是超出指定列表长度,那么这个元素一定会被放在列表的最后位置

remove()1list.remove('grape')

或者1

2

3list = ['pineapple','grape','pear']

del list[0:2]

print(list)

输出[‘pear’]

索引

字典(Dictionary)

key - value字典中数据必须是以key-value的形式出现的

逻辑上讲,key不能够重复,而value可以重复

字典中的key是不可以修改的;而value是可以修改的,可以是任何对象1dict = {'key1':'val1', 'key2':'val2'}

添加键值对1dict['key3'] = 'val3'

update()添加多个元素

update()方法可以用来添加多个元素1dict.update({'key4':'val4', 'key5':'val5'})

del删除元素1del dict['key2']

元组(Tuple)

元组可以理解成一个稳固版的列表,因为元组是不可修改的,因此在列表中的存在的方法均不可以使用在元组上,但是元组是可以被查看索引的,方式和列表中一样:1

2letters = ('a','b','c','d','e','f','g')

letter[0]

集合(Set)1a_set = {1,2,3,4}

每一个集合中的元素是无序的、不重复的任意对象,我们可以通过集合去判断数据的从属关系,有时还可以通过集合把数据结构中重复的元素减掉

集合不能被切片也不能被索引,除了做集合运算之外,集合元素可以被添加还有删除1

2

3

4a_set.add(5)

print('after add:' + str(a_set))

a_set.discard(5)

print('after discard:' + str(a_set))

输出after add:{1, 2, 3, 4, 5}

after discard:{1, 2, 3, 4}

数据结构中的一些技巧

多重循环1

2num_list = [6,2,7,4,1,3,5]

print(sorted(num_list))

输出[1, 2, 3, 4, 5, 6, 7]

sorted函数按照长短、大小、英文字母的顺序给每个列表中的元素进行排序sorted函数并不会改变列表本身,你可以把它理解成先将列表进行复制,然后再进行顺序的整理

在使用默认参数reverse后列表可以被按照逆序整理:1

2num_list = [6,2,7,4,1,3,5]

print(sorted(num_list, reverse=True))

输出[7, 6, 5, 4, 3, 2, 1]

关键字zip处理两个list1

2

3

4name=('jack','beginman','sony','pcky')

age=(2001,2003,2005,2000)

for n,a in zip(name,age):

print (n, '--', a)

输出jack – 2001

beginman – 2003

sony – 2005

pcky – 2000

推导式

红色虚线后面的是我们熟悉的for循环的表达式,而虚线前面的可以认为是我们想要放在列表中的元素1

2

3

4a = [i**2 for i in range(1,10)]

c = [j+1 for j in range(1,10)]

k = [n for n in range(1,10) if n % 2 ==0]

z = [letter.lower() for letter in 'ABCDEFGHIGKLMN'

字典推导式的方式略有不同,主要是因为创建字典必须满足key-value的两个条件才能达成1

2

3d = {i:i+1 for i in range(4)

g = {i:j for i,j in zip(range(1,6),'abcde')}

g = {i:j.upper() for i,j in zip(range(1,6),'abcde')}

enumerate获取元素的索引1

2

3letters = ['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

一个词频统计的小程序1

2

3

4

5

6

7

8

9

10import string

path = 'G:Python_CodeTestWalden.txt'

with open(path, 'r') as text:

# 文字首位去掉了连在一起的标点符号,并把首字母大写的单词转化成小写

words = [raw_word.strip(string.punctuation).lower() for raw_word in text.read().split()]

words_index = set(words) # 将列表用set函数转换成集合,自动去除掉了其中所有重复的元素

counts_dict = {index:words.count(index) for index in words_index}

# 排序后输出

for word in sorted(counts_dict, key=lambda x: counts_dict[x], reverse=True):

print('{} -- {} times'.format(word,counts_dict[word]))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值