In Python 3, I defined two paths using pathlib, say:
from pathlib import Path
origin = Path('middle-earth/gondor/minas-tirith/castle').resolve()
destination = Path('middle-earth/gondor/osgiliath/tower').resolve()
Run Code Online (Sandbox Code Playgroud)
How can I get the relative path that leads from origin to destination? In this example, I'd like a function that returns ../../osgiliath/tower or something equivalent.
Ideally, I'd have a function relative_path that always satisfies
origin.joinpath(
relative_path(origin, destination)
).resolve() == destination.resolve()
Run Code Online (Sandbox Code Playgroud)
(well, ideally there would be an operator - such that destination == origin / (destination - origin) …
根据此答案,在Python 3.5或更高版本中,可以合并两个字典x并y解压缩它们:
z = {**x, **y}
Run Code Online (Sandbox Code Playgroud)
是否可以解压缩各种字典表?就像是
def merge(*dicts):
return {***dicts} # this fails, of course. What should I use here?
Run Code Online (Sandbox Code Playgroud)
例如,我希望
list_of_dicts = [{'a': 1, 'b': 2}, {'c': 3}, {'d': 4}]
{***list_of_dicts} == {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Run Code Online (Sandbox Code Playgroud)
请注意,此问题不是关于如何合并字典列表的问题,因为上面的链接提供了对此的答案。这里的问题是:是否有可能以及如何解压缩字典列表?
正如评论指出,这个问题是非常相似的这一个。但是,解压缩字典列表与简单地合并它们是不同的。假设有一个运算符***旨在解开字典列表,并给出
def print_values(a, b, c, d):
print('a =', a)
print('b =', b)
print('c =', c)
print('d =', d)
list_of_dicts = [{'a': 1, 'b': …Run Code Online (Sandbox Code Playgroud)