010-python 的一些小知识点

python 的一些小知识点

1、删除列表中连续的几个元素

letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
letters[2:5] = ""	# 这里使用 [],(),{} 都可以
print(letters) 		# ['a', 'b', 'f', 'g']

2、编写【斐波那契数列】的初始子序列

def fblt():
    lt = []
    a, b = 0, 1
    while a < 10:
        lt.append(a)
        a, b = b, a + b
    print(lt)   # [0, 1, 1, 2, 3, 5, 8]

3、return None
如果 return 后不跟任何表达式参数,则会返回 None。

4、函数参数默认值之可变对象
重要警告:函数参数默认值只会执行一次。这条规则在默认值为可变对象(列表、字典以及大多数类实例)时很重要。比如,下面的函数会存储在后续调用中传递给它的参数:

def f(a, L=[]):
    L.append(a)
    return L

print(f(1))		# [1]
print(f(2))		# [1, 2]
print(f(3))		# [1, 2, 3]

如果不想要在后续调用之间共享默认值,你可以这样写这个函数:

def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L

# def f(a, L=None):
def f(a, L=[]):
    if not L:
        L = []
    L.append(a)
    return L

5、解包参数列表

list(range(3, 6))		# [3, 4, 5]

args = [3, 6]
list(range(*args))		# [3, 4, 5]

def parrot(voltage, state='stateA', action='actionA'):
    print(voltage)  # voltageB
    print(state)    # stateB
    print(action)   # actionB

d = {"voltage": "voltageB", "state": "stateB", "action": "actionB"}
parrot(**d)

6、Lambda 表达式

def make_incrementor(n):
    return lambda x: x + n

f = make_incrementor(42)
f(0)	# 42
f(1)	# 43


a = lambda x: x ** 2
print(a(10))  # 100

f = lambda x, y, z: x + y + z
res = f(1, 2, 3)  # 6

g = lambda x, y=2, z=3: x + y + z
res = g(1, z=4, y=5)  # 10

lt = [lambda x: x ** 2, lambda x: x ** 3, lambda x: x ** 4]
res = lt[0](3)  # 9
res = lt[1](3)  # 27
res = lt[2](3)  # 81

lt = [1, 2, 3, 4, 5]
res = map(lambda x: x ** 2, lt)
print(list(res))  # [1, 4, 9, 16, 25]

fc = lambda: print(123)
fc()  # 123

上面的例子使用一个lambda表达式来返回一个函数。另一个用法是传递一个小函数作为参数:

pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
pairs	# [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

7、函数标注
函数标注 是关于用户自定义函数中使用的类型的完全可选元数据信息(有关详情请参阅 PEP 3107PEP 484 )。

函数标注 以字典的形式存放在函数的 annotations 属性中,并且不会影响函数的任何其他部分。 形参标注的定义方式是在形参名称后加上冒号,后面跟一个表达式,该表达式会被求值为标注的值。 返回值标注的定义方式是加上一个组合符号 ->,后面跟一个表达式,该标注位于形参列表和表示 def 语句结束的冒号之间。
下面的示例有一个位置参数,一个关键字参数以及返回值带有相应标注:

def annotFunc(ham: str, eggs: str = 'eggs') -> list:
    print("Annotations:", annotFunc.__annotations__)
    print("Arguments:", ham, eggs)
    return [ham , eggs]
    
annotFunc('spam')

打印结果:
Annotations: {'ham': <class 'str'>, 'eggs': <class 'str'>, 'return': <class 'list'>}
Arguments: spam eggs

8、删除列表元素

lt = ['a', 'b', 'c', 'a', 'd', 'c']
lt.pop(2)
print(lt)       # ['a', 'b', 'a', 'd', 'c']

lt.remove('a')
print(lt)       # ['b', 'a', 'd', 'c']

lt.clear()      # 与 del lt[:] 等价
print(lt)       # []

del lt			# 删除 lt 列表对象,lt 不存在了

9、列表的使用
1)列表作为栈使用
列表方法使得列表作为堆栈非常容易,最后一个插入,最先取出(“后进先出”)。要添加一个元素到堆栈的顶端,使用 append() 。要从堆栈顶部取出一个元素,使用 pop() ,不用指定索引。例如

stack = [3, 4, 5]
stack.append(6)
stack.append(7)
stack			# [3, 4, 5, 6, 7]

stack.pop()		# 7
stack.pop()		# 6

2)列表作为队列使用
列表也可以用作队列,其中先添加的元素被最先取出 (“先进先出”);然而列表用作这个目的相当低效。因为在列表的末尾添加和弹出元素非常快,但是在列表的开头插入或弹出元素却很慢 (因为所有的其他元素都必须移动一位)。

若要实现一个队列, collections.deque 被设计用于快速地从两端操作。例如

from collections import deque

queue = deque(["Eric", "John", "Michael"])
queue.append("Terry")
queue.append("Graham")

queue               # deque(['Eric', 'John', 'Michael', 'Terry', 'Graham'])
queue.popleft()     # 'Eric'
queue.popleft()     # 'John'
queue               # deque(['Michael', 'Terry', 'Graham'])

10、列表推导式

combs = []
for x in [1,2,3]:
    for y in [3,1,4]:
        if x != y:
            combs.append((x, y))

combs	# [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

》》等价于
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]

11、赋值

a = 1, 2, 3
print(a)        # (1, 2, 3)

b = a, ('tom', 'cat')
print(b)        # ((1, 2, 3), ('tom', 'cat'))

c, d = 5, 6
print(c)        # 5
print(d)        # 6

e = 'dufu',
print(e)        # ('dufu',)

f, g = ('name', 'age')  # 元组解包
print(f)        # name
print(g)        # age

12、集合的使用

a = set('abracadabra')
b = set('alacazam')
print(a)        # {'b', 'c', 'r', 'd', 'a'}
print(b)        # {'c', 'l', 'a', 'm', 'z'}

print(a - b)    # {'r', 'b', 'd'}   【差集】
print(a | b)    # {'r', 'l', 'z', 'b', 'd', 'a', 'm', 'c'}  【并集】
print(a & b)    # {'a', 'c'}    【交集】
print(a ^ b)    # {'r', 'l', 'm', 'z', 'b', 'd'}    【并集-交集】

13、利用列表提取字典所有 key
对一个字典执行 list(d) 将返回包含该字典中所有键的列表,按插入次序排列 。

dt = {"id":10, "age":20, "name":"tom"}
lt = list(dt)
print(lt)   # ['id', 'age', 'name']

14、dict 的妙用

dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'guido': 4127, 'jack': 4098}

dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'guido': 4127, 'jack': 4098}

15、比较操作符
比较操作符 in 和 not in 校验一个值是否在(或不在)一个序列里。操作符 is 和 is not 比较两个对象是不是同一个对象,这只跟像列表这样的可变对象有关。所有的比较操作符都有相同的优先级,且这个优先级比数值运算符低。

比较操作可以传递。例如 a < b == c 会校验是否 a 小于 b 并且 b 等于 c。

a, b, c = 1, 2, 2
if a < b == c:
    print('true..')
else:
    print('false..')
    
打印:
true..

string1, string2, string3 = '', 'AA', 'BB'
non_null = string1 or string2 or string3
print(non_null)     # AA

16、序列和其它类型的比较
序列对象可以与相同类型的其他对象比较。它们使用 字典顺序 进行比较:首先比较两个序列的第一个元素,如果不同,那么这就决定了比较操作的结果。如果它们相同,就再比较每个序列的第二个元素,以此类推,直到有一个序列被耗尽。如果要比较的两个元素本身就是相同类型的序列,那么就递归进行字典顺序比较。如果两个序列中所有的元素都相等,那么我们认为这两个序列相等。如果一个序列是另一个序列的初始子序列,那么短序列就小于另一个。字典顺序对字符串来说,是使用单字符的 Unicode 码的顺序。下面是同类型序列之间比较的例子

(1, 2, 3)              < (1, 2, 4)
[1, 2, 3]              < [1, 2, 4]
'ABC' < 'C' < 'Pascal' < 'Python'
(1, 2, 3, 4)           < (1, 2, 4)
(1, 2)                 < (1, 2, -1)
(1, 2, 3)             == (1.0, 2.0, 3.0)
(1, 2, ('aa', 'ab'))   < (1, 2, ('abc', 'a'), 4)


if (1, 2, 3) < (1, 2, 4):
    print(11)

17、在数字中使用下划线
python 3.6 支持新的数字下划线功能,以提高可读性。
在数字之间和任何基本说明符之后允许单下划线。

salary = 123_456_78
print(salary)   # 12345678

salary2 = '{:_}'.format(12345678)
print(salary2)  # 12_345_678

salary3 = '{:,}'.format(12345678)
print(salary3)  # 12,345,678

18、格式化字符串文字 f/F
f-string 用法
格式化字符串字面值 (常简称为 f-字符串)能让你在字符串前加上 f 和 F 并将表达式写成 {expression} 来在字符串中包含 Python 表达式的值。
(1) '!a' 应用 ascii()'!s' 应用 str(),还有 '!r' 应用 repr()

!s:str(),返回对象的字符串表示形式,如果字符串是已编码,返回的是解码后的字符串。转换过后的字符串最外层不带引号,如 abc
!r:repr(),返回对象的规范字符串表示形式。转换过后的字符串最外层带引号,如 'abc'
    注意:对于许多对象类型,包括大多数内建,eval(repr(obj)) == obj
!a:ascii(),返回对象的纯 ascii 表示形式,但要使用\\x、\\u或\\U转义转义所返回字符串中的非 ascii 字符。
name = 'tom'
nr = f'{name!r}'
na = f'{name!a}'
print(name)     # tom
print(nr)       # 'tom'
print(na)       # 'tom'

name = 'tom@cat中文'
nr = f'{name!r}'
na = f'{name!a}'
print(name)     # tom@cat中文
print(nr)       # 'tom@cat中文'
print(na)       # 'tom@cat\u4e2d\u6587'
str_ = "12aA中国"
a = ascii(str_)     # '12aA\u4e2d\u56fd'
b = repr(str_)      # '12aA中国'
c = str('\u56fd')   # 国
d = repr('\u56fd')  # '国'
e = eval(b)         # 12aA中国

t = "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
print(t)    # repr() shows quotes: 'test1'; str() doesn't: test2
t2 = "repr() shows quotes: {0!r}; str() doesn't: {1!s}".format('test1', 'test2')
print(t2)   # repr() shows quotes: 'test1'; str() doesn't: test2

str(str_) == str_        # True
repr(str_) == str_       # False

len(str(str_))          # 6
len(repr(str_))         # 8

(2)

date = datetime.datetime(1991, 10, 12, 13, 26, 38)
print(date)     # 1991-10-12 13:26:38

res = f'{date:%Y-%m-%d %H:%M:%S}'
print(res)      # 1991-10-12 13:26:38

res2 = f'{date:%X}'
print(res2)     # 13:26:38

day = f'{date:%j}'
print(day)      # 285

day = f'{date:%A}'
print(day)      # Saturday

19、比较操作可以传递
a < b == c 会校验是否 a 小于 b 并且 b 等于 c。

19、python 有哪些关键字

import keyword
kws = keyword.kwlist
print(kws)

['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 
'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 
'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值