[Python 实战] - No.13 Python高级编程

Python高级编程

记录一下python中几种比较高效、简洁的编程方法

变量交换:

在其他语言中,我们进行变量交换一般都是使用一个临时存储变量tmp,然后将a,b的变量值进行交换。但是python独有一种超级简单的变量交换的方法。

a = 5
b = 10
print(a,b)

b,a = a,b
print(a,b)

'''
5 10
10 5
'''

还有几种其他的有有趣的方式进行变量交换,但并非python特有。

加和方法:

a = 5
b = 10
print(a,b)
a = a + b #15
b = a - b #5
a = a - b #10
print(a,b)

异或方法:

a = 5   #0101
b = 10  #1010
print(a,b)
a = a^b #1111
b = a^b #0101
a = a^b #1010
print(a,b)
遍历两个列表:

zip() 函数用于将可迭代对象作为参数,将对象中对应的元素打包成一个个元组,然后


teamA = ['Alice','Bob','Cindy']
teamB = ['David','Frank','Gale']

for t1,t2 in zip(teamA,teamB):
    print(t1+" likes " +t2)
    
'''
Alice likes David
Bob likes Frank
Cindy likes Gale
'''
推导式(comprehensions):

python推导式又称解析式,是python的一种特性。推导式能让python开发者,根据已有的数据集合快速构建另一个数据集合。我们常用的有以下三种推导式:列表推导式、字典推导式和集合推导式。

列表推导式:

# 快速创建 20以内的奇数数组
odd = [i for i in range(20) if i%2==1]
print(odd)

'''
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
'''

我们还可以将列表生成元素表达式用函数代替,如下所示:

def func(i):
    return "Odd_Num:" + str(i)
odd_num = [func(i) for i in range(20) if i%2==1]
print(odd_num)

'''
['Odd_Num:1', 'Odd_Num:3', 'Odd_Num:5', 'Odd_Num:7', 'Odd_Num:9', 'Odd_Num:11', 'Odd_Num:13', 'Odd_Num:15', 'Odd_Num:17', 'Odd_Num:19']
'''

集合推导式:

集合推导式和列表推导式形式是很相似的,只不过集合推导式需要使用**{}**

odd = {i for i in range(20) if i%2==1}
print(odd)

字典推导式:

# 获取所有的英文名以'A'开头的员工姓名和ID字典

names = ['Alice','Abby','Alex','Bob','Cindy']
ids = ['0312','0315','0396','1256','2357']
name_dict = {Name:Id for Name,Id in zip(names,ids) if Name[0]=='A'}
print(name_dict)

'''
{'Alice': '0312', 'Abby': '0315', 'Alex': '0396'}
'''

利用字典推导式,我们可以在python中实现快速的key,value互换

id_name = {v:k for k,v in name_dict.items() }
print(id_name)

'''
{'0312': 'Alice', '0315': 'Abby', '0396': 'Alex'}
'''
Counter计数器

python的collections模块提供了一些特殊容器,Counter就是其中很有用的一个类,可以很方便地计算列表和字符串中的词频等。

from collections import Counter

sentence_set = """When forty winters shall besiege thy brow,
And dig deep trenches in thy beauty's field,
Thy youth's proud livery so gazed on now,
Will be a totter'd weed of small worth held:
Then being asked, where all thy beauty lies,
Where all the treasure of thy lusty days;
To say, within thine own deep sunken eyes,
Were an all-eating shame, and thriftless praise.
How much more praise deserv'd thy beauty's use,
If thou couldst answer 'This fair child of mine
Shall sum my count, and make my old excuse,'
Proving his beauty by succession thine!
This were to be new made when thou art old,
And see thy blood warm when thou feel'st it cold.""".split()

cnt = Counter(sentence_set)
print(cnt.most_common(5))

'''
[('thy', 6), ('of', 3), ('thou', 3), ('And', 2), ('deep', 2)]
'''

另外,由于Counter是dict的子类,所以很多dict上的操作同样适用于Counter

print(cnt.items()) #(k,v)格式列表,可以很方便遍历
list(cnt)  # 将cnt中的键转为列表
set(cnt)  # 将cnt中的键转为set
dict(cnt)  # 将cnt中的键值对转为字典
行内if语句
gender = 'male'
likes = "toy" if gender=='female' else 'bike'
print(likes)

python中的行内if语句有点像c++中的三元表达式,都是很简单的一种if方法。我们可以使用行内if语句来非常简单的实现一个经典问题"fizzbuzz"

**FizzBuzz:**写一个程序,打印数字1到100,3的倍数打印“Fizz”来替换这个数,5的倍数打印“Buzz”,对于既是3的倍数又是5的倍数的数字打印“FizzBuzz”。

for i in range(1,101):
    print('fizz'*(i%3==0)+'buzz'*(i%5==0) if i%3==0 or i%5==0 else i)
    
'''
1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
......
'''
数值比较:

python中的数值比较语法显得特别的优秀!

for i in range(20):
    if 3 < i <10:
        print(i,end=',')
    if 10 < i > 15:
        print(i,end=',')     
		
'''
4,5,6,7,8,9,16,17,18,19,
'''
字典索引:

在python中,我们经常用下列方法获取dict元素:

d = {'Alice': '0312', 'Abby': '0315', 'Alex': '0396'}
key1 = 'Alice'
try:
    id1 = d[key1]
except KeyError:
    print("No such key")
    id1 = None

使用索引,如果索引不存在抛出异常,然后进行赋值。也可以使用get()方法来获取并设置键值不存在时候的默认值。

id1= d.get(key1,None)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值