对于 max 和 min 可以比较数值大小这一点大家肯定都是十分熟悉,除此之外 max 和 min 同样也可以比较 list 和 str 大小.
文档说明
首先看一下 max 和 min 的说明文档
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
max(...) max(iterable, *[, default=obj, key=func]) -> value max(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its biggest item. The default keyword-only argument specifies an object to returnif the provided iterable is empty. With two or more arguments, return the largest argument. min(...) min(iterable, *[, default=obj, key=func]) -> value min(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its smallest item. The default keyword-only argument specifies an object to returnif the provided iterable is empty. With two or more arguments, return the smallest argument.
从上面的文档不难看出,max 和 min 对 iterable 对象的支持,那么对 List 是如何比较的呢?看个例子
classSolution: deflongestCommonPrefix(self, strs: 'List[str]') -> 'str': ifnot strs: return'' s1 = min(strs) s2 = max(strs) ans = "" for i, v inenumerate(s1): if v != s2[i]: return s1[:i] return s1
很显然简单的使用 a 或者 a+ 模式是做不到上述要求的,有兴趣的可以自己尝试一下,它们只是简单的追加内容到上次文件末尾
实践
针对上述例子的要求,最容易想到的方案就是: 1.先以 r 的模式,打开文件读取文件数据,得到 dictA 2.然后以 w 的模式,打开文件,将本次数据 dictB 与 dictA 合并后写入 dictA
首先肯定这种方案没有任何问题,能够解决问题,不过这显然不是最佳方案,因为多次打开文件,增加了 IO 的开销,那有没有只打开一次文件完成上述要求呢?显然是有的,再说解决方案之前,我们先说一下预备知识:为什么 a 模式下可以追加内容到文件末尾? 因为在 a 模式下,打开文件后,文件指针默认指向文件末尾.ok了,新的方案就这么出来了.
新的方案基于文件指针,我们以 a 或者 a+ 模式打开文件,将文件指针移动到文件开头,读取文件内容,然后合并数据,然后清除文件内容,重新写入合并后的数据.最后看一下代码
1 2 3 4 5 6 7 8 9 10 11
import json import os new_dict = {'c':'d'} old_dict = {} withopen('test.json','a+') as f: if os.path.getsize('test.json'): f.seek(0) # 重点,移动指针 old_dict = json.load(f) merge_dict = {**old_dict,**new_dict} f.truncate(0) # 清空之前内容 json.dump(merge_dict,f)
error[E0282]: type annotations needed --> src/main.rs:2:9 | 2 | let guess = "42".parse().expect("Not a number!"); | ^^^^^ | | | cannot infer type for `_` | consider giving `guess` a type
fnmain() { let x = 0; { let x = 1; println!("Inner x: {}", x); // prints 1 } println!("Outer x: {}", x); // prints 0 // Shadow let x = "Rust"; println!("Outer x: {}", x); // prints 'Rust' }
_future_ is a real module, and serves three purposes:
To avoid confusing existing tools that analyze import statements and expect to find the modules they’re importing.
To ensure that future statements run under releases prior to 2.1 at least yield runtime exceptions (the import of __future__ will fail, because there was no module of that name prior to 2.1).
To document when incompatible changes were introduced, and when they will be — or were — made mandatory. This is a form of executable documentation, and can be inspected programmatically via importing __future__ and examining its contents.