Python 小技巧 1-10

  1. 交换两个数字
>>> x, y = 10, 20
>>> print(x, y)
10 20
>>> x, y = y, x
>>> print(x, y)
20 10
  1. 反转字符串
>>> a = "Hello World!"
>>> print("反转字符串:",a[::-1])
反转字符串: !dlroW olleH
  1. 用列表中的所有元素创建一个字符串
>>> a = ["Hello","World","!"]
>>> print(" ".join(a))
Hello World !
  1. 打印导入模块的文件路径
>>> import os
>>> print(os)
<module 'os' from 'C:\\ProgramData\\Anaconda3\\lib\\os.py'>
  1. 从函数返回多个值
>>> def x():
...     return 1,2,3,4
...
>>> a,b,c,d = x()
>>> print(a,b,c,d)
1 2 3 4
  1. 在列表中找到最频繁的值
>>> test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
>>> print(max(set(test), key = test.count))
4
  1. 使用三元运算符进行条件赋值
    三元运算符是 if-else 语句的快捷方式,也称为条件运算符。
[on_true] if [expression] else [on_false]

以下是一些示例,您可以使用它们使代码紧凑简洁。

下面的语句与它的意思相同,即“如果 y 为 9,则将 10 分配给 x,否则将 20 分配给 x”。 如果需要,我们可以扩展运算符的链接。

x = 10 if (y == 9) else 20

同样,我们可以对类对象做同样的事情。

x = (classA if y == 1 else classB)(param1, param2)

在上面的例子中,A 类和 B 类是两个类,其中一个类构造函数将被调用。
下面的例子,返回三个数中最小的数。

>>> def small(a,b,c):
...     return a if a <= b and a <= c else (b if b <= a and b <= c  else c)
...
>>> print(small(1,0,1))
0
>>> print(small(1,2,2))
1
>>> print(small(2,2,3))
2
>>> print(small(5,4,3))
3

我们甚至可以在列表推导式中使用三元运算符,如下:

>>> [m**2 if m > 10 else m**4 for m in range(50)]
[0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401]
  1. 使用多行字符串
    基本方法是使用从 C 语言派生的反斜杠。
>>> multiStr = "select * from multi_row \
... where row_id < 5"
>>> print(multiStr)
select * from multi_row where row_id < 5

另一个技巧是使用三重引号

>>> multiStr = """select * from multi_row
... where row_id < 5"""
>>> print(multiStr)
select * from multi_row
where row_id < 5

上述方法的共同问题是缺乏适当的缩进。 如果我们尝试缩进,它会在字符串中插入空格。

所以最终的解决方案是将字符串拆分成多行,并将整个字符串括在括号中。

>>> multiStr= ("select * from multi_row "
... "where row_id < 5 "
... "order by age")
>>> print(multiStr)
select * from multi_row where row_id < 5 order by age
  1. 将序列分解为单独的变量
    任何的序列(或者是可迭代对象)可以通过一个简单的赋值操作来分解为单独的变量。 唯一的要求就是变量的总数和结构必须与序列相吻合。
>>> testList = [1,2,3]
>>> x,y,z = testList
>>> print(x,y,z)
1 2 3
>>> data = [ 'ACME', 50, 91.1, (2012, 12, 21) ]
>>> name, shares, price, date = data
>>> name
'ACME'
>>> date
(2012, 12, 21)
>>> name, shares, price, (year, mon, day) = data
>>> name
'ACME'
>>> year
2012
>>> mon
12
>>> day
21

如果元素的数量不匹配,会得到一个错误提示。

  1. 将序列分解为多个变量
    如果元素的数量不匹配,会得到一个错误提示。星号表达式可以用来解决这个问题。
>>> record = ('Dave', 'dave@example.com', '773-555-1212', '847-555-1212')
>>> name,email,*phone_numbers = record
>>> name
'Dave'
>>> email
'dave@example.com'
>>> phone_numbers
['773-555-1212', '847-555-1212']

phone_numbers 变量永远都是列表类型。
星号表达式也能用在列表的开始部分。比如,你有一个公司前 8 个月销售数据的序列, 但是你想看下最近一个月数据和前面 7 个月的平均值的对比。你可以这样做:

*trailing_qtrs, current_qtr = sales_record
trailing_avg = sum(trailing_qtrs) / len(trailing_qtrs)
return avg_comparison(trailing_avg, current_qtr)

下面是在 Python 解释器中执行的结果:

>>> *trailing, current = [10, 8, 7, 1, 9, 5, 10, 3]
>>> trailing
[10, 8, 7, 1, 9, 5, 10]
>>> current
3
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值