小编rug*_*tal的帖子

How to get the relative path between two absolute paths in Python using pathlib?

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 python-3.x pathlib

5
推荐指数
1
解决办法
80
查看次数

解压Python中的字典列表

根据此答案,在Python 3.5或更高版本中,可以合并两个字典xy解压缩它们:

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)

python merge dictionary python-3.x

4
推荐指数
3
解决办法
71
查看次数

标签 统计

python ×2

python-3.x ×2

dictionary ×1

merge ×1

pathlib ×1