set 和 dict 的元素顺序
集合没有顺序保证,因此不能依赖元素按特定顺序出现。
从 Python 3.7 起,字典保证保留插入顺序。在 Python 3.6 及更早版本的语言规范中没有这项保证。
列表切片
这里讨论的是切片结果与原列表内部元素之间的关系。
我在 T. A. 的回答中看到下面这个例子,觉得很有意思。
from typing import List
def buddle_sort(lst: List):
if len(lst) < 2:
return lst#changed
i = 0
while i < len(lst) - 1:
if lst[i+1] < lst[i]:
lst[i], lst[i+1] = lst[i+1], lst[i]
i += 1
return buddle_sort(lst[:len(lst)-1])#changed to prevent returning None when if block isn't executed
a = [100, 8, 3, 4, 6]
a = buddle_sort(a)#changed
print(a)
a[len(a):] = [1, 2]
print(a)
T. A.(2022 年 3 月)在回复 @kingluo 时写道:“我认为切片返回的是原列表里面的列表,而不是复制的列表。不过你的代码里有函数会编辑作为参数传入的列表。使用参数时,要分清对形参的操作会怎样影响传入的原变量。可以试着运行这个简单的例子来理解。” 来源:discuss.python.org。https://discuss.python.org/t/does-the-list-slicing-produce-a-new-list/14627
not 运算符
>>> # Bad practice
>>> not "c" in ["a", "b", "c"]
False
>>> # Best practice
>>> "c" not in ["a", "b", "c"]
False
>>> obj = None
>>> # Bad practice
>>> not obj is None
False
>>> # Best practice
>>> obj is not None
False
假设要判断给定字符是不是数字。既然已经有了 NON_NUMERIC,你可能会想到用 not 来检查条件:
if char not in NON_NUMERIC:
number = float(char)
# Do further computations...
这样的代码读起来很怪,实际编程中大概不会特意这么写。不过有时确实容易写出类似上面的表达式。
这个例子用了双重否定:NON_NUMERIC 已经带有否定的含义,外面又加了 not,读者得多想一层。遇到这种情况,可以试着把条件写成肯定句,或者至少去掉一层否定。
- Leodanis Pozo Ramos. (Oct 25, 2021.). Using the "not" Boolean Operator in Python. realpython. [Blog post]. Retrieved from https://realpython.com/python-not-operator/
Python 的 for … in 循环
for i in []:
#code in this loop block will not be excuted
如果要遍历的列表或集合为空,则直接跳过整个循环,循环体中的语句一次也不会执行。
延伸阅读
- Vijayasekhar Deepak. (Aug 27, 2023). What happens when you apply for loop, reduce, forEach and map for empty list in Dart. Medium. [Blog post]. Retrieved from https://tarzzotech.medium.com/what-happens-when-you-apply-for-loop-reduce-foreach-and-map-for-empty-list-in-dart-92113d867094
Python 的 for … else
如果循环没有通过 break 退出,便会执行 else 块。
- Helperhaps. (19 June, 2018.). Python 的 For/Else 语句. 知乎专栏. [Blog post]. Retrieved from https://zhuanlan.zhihu.com/p/37374055
Python 的精度处理
用 format:
format(0.1, '.17f')
# output'0.10000000000000001'
用 Decimal:
from decimal import *
getcontext().prec = 6
Decimal(1) / Decimal(7)
# output Decimal('0.142857')
getcontext().prec = 28
Decimal(1) / Decimal(7)
# output Decimal('0.1428571428571428571428571429')
用 Fraction: 需要更精确的结果时,可以使用分数。fractions 模块文档
两个内置测试库
https://docs.python.org/3/library/unittest.html
https://docs.python.org/3/library/doctest.html#module-doctest