Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从字典键和它生成元组';s值_Python_Dictionary - Fatal编程技术网

Python 从字典键和它生成元组';s值

Python 从字典键和它生成元组';s值,python,dictionary,Python,Dictionary,我有每个键映射到列表的字典列表 [ {28723408: [28723409]}, {28723409: [28723410]}, {28723410: [28723411, 28723422]}, {28723411: [28723412]}, {28723412: [28723413]}, {28723413: [28723414, 28, 28723419]}] 我想创建映射到每个列表值的元组键列表: [(28723408, 287

我有每个键映射到列表的字典列表

[    {28723408: [28723409]},
     {28723409: [28723410]},
     {28723410: [28723411, 28723422]},
     {28723411: [28723412]},
     {28723412: [28723413]},
     {28723413: [28723414, 28, 28723419]}]
我想创建映射到每个列表值的元组键列表:

[(28723408, 28723409),
 (28723409, 28723410),
 (28723410, 28723411),
 (28723410, 28723422),
 (28723411, 28723412),
 (28723412, 28723413),
 (28723413, 28723414),
 (28723413, 28),
 (28723413, 28723419),]
我是这样做的:

for pairs in self.my_pairs:
    for source, targets in pairs.items():
        for target in targets:
            pair_list.append((source, target))

有没有比这更像蟒蛇的方式呢?

我会完全按照你已经做过的去做,但要使用列表理解

pair_list = [(source, target)
             for pairs in self.my_pairs
             for source, targets in pairs.items()
             for target in targets]
这种方法看起来可能与您的方法相同,但速度要快得多!检查例如问题(或)。这一事实也得到了证实

如果您想要一种更“pythonic”的方法,您还可以使用
itertools.product
itertools.chain

from itertools import chain, product

pair_list = list(chain(*(product((source,), targets)
                         for pairs in self.my_pairs
                         for source, targets in pairs.items())))

我尝试过的所有花哨的OneLiner最终都不如你所做的那么可读。你的字典列表中的键是否已知是不同的?否则会发生什么?@guidot,它们不是不同的。我只需要使映射不需要过滤器。每个dict是否都有一个单独的键?@RiccardoBucco,请不要这样假设。我正要使用列表理解发布类似的答案。很不错的!