解包字典嵌套列表

时间:2021-06-24 07:29:52

标签: python list product itertools nested-lists

我正在尝试为嵌套列表中的每个列表获取所有可能的组合。 我已经尝试了下面的代码,但它正在打印一个空列表

import json
from pprint import pprint
import itertools


variant = [[{"Typ": "Bridge"}, {"Typ": "Media"}, {"Typ": "Tower"}], [{"Kabeleinf\u00fchrung": "Kabelverschraubung Kunststoff \u00d8 79 mm"}, {"Kabeleinf\u00fchrung": "Power T\u00fclle Twist \u00d8 80 mm"}, {"Kabeleinf\u00fchrung": "Power Grommet Twist USB Daten / Ladung \u00d8 80 mm"}, {"Kabeleinf\u00fchrung": "Power T\u00fclle GST 18 \u00d8 80 mm"}], [{"Whiteboard": "Ohne"}, {"Whiteboard": "Mitt"}], [{"::gote::gote::@GGOTE_WhiteboardShelf": "Ohne"}, {"::gote::gote::@GGOTE_WhiteboardShelf": "Mitt"}], [{"TV-Halterung": "Ohne"}, {"TV-Halterung": "Mitt"}], [], [{"Stoff": "Event screen + (Preisklasse 1)"}, {"Stoff": "Cara (Preisklasse 1)"}, {"Stoff": "Carlow (Preisklasse 1)"}, {"Stoff": "Pearl (Preisklasse 1)"}, {"Stoff": "Omega (Preisklasse 1)"}, {"Stoff": "Xpress (Preisklasse 1)"}, {"Stoff": "Hush (Preisklasse 1)"}, {"Stoff": "Mica (Preisklasse 1)"}, {"Stoff": "Slope (Preisklasse 1)"}, {"Stoff": "Noble Lux (Preisklasse 2)"}, {"Stoff": "Houston Reflect (Preisklasse 2)"}, {"Stoff": "Kunstleder (Preisklasse 2)"}, {"Stoff": "Lido (Preisklasse 2)"}, {"Stoff": "Twist (Preisklasse 2)"}, {"Stoff": "Rivet (preisklasse 2)"}, {"Stoff": "Blazer (Preisklasse 3)"}, {"Stoff": "Blazer Lite (pris gruppe 3)"}, {"Stoff": "Synergy (Preisklasse 3)"}, {"Stoff": "Bond (Preisklasse 3)"}, {"Stoff": "Hint (Preisklasse 3)"}, {"Stoff": "Remix 3 (preisklasse 4)"}, {"Stoff": "Step (Preisklasse 4)"}], [{"Stofffarbe": "01 (60000 BY GABRIEL)"}, {"Stofffarbe": "02 (61008 BY GABRIEL)"}, {"Stofffarbe": "03 (61011 BY GABRIEL)"}, {"Stofffarbe": "04 (60004 BY GABRIEL)"}, {"Stofffarbe": "05 (60002 BY GABRIEL)"}, {"Stofffarbe": "06 (60021 BY GABRIEL)"}, {"Stofffarbe": "07 (60999 BY GABRIEL)"}, {"Stofffarbe": "08 (67015 BY GABRIEL)"}, {"Stofffarbe": "09 (67017 BY GABRIEL)"}], [{"Type": "110010"}]]

print(list(itertools.product(*variant)))

这是我当前的代码。

[('Typ--Bridge','Kabeleinführung--Kabelverschraubung Kunststoff Ø 79 mm', 'Whiteboard--Ohne'),('Typ--Bridge','Kabeleinführung--Kabelverschraubung Kunststoff Ø 79 m', 'Whiteboard--Mitt'),('Typ--Bridge', 'Kabeleinführung--Power Tülle Twist Ø 80 mm', 'Whiteboard--Ohne'), ('Typ--Bridge', 'Kabeleinführung--Power Tülle Twist Ø 80 mm',
'Whiteboard--Mitt'),                                         

这就是我希望输出的样子。 似乎问题在于嵌套列表的解包,当我单独运行时,它没有用逗号分隔,但我无法弄清楚究竟出了什么问题。

1 个答案:

答案 0 :(得分:2)

检查 variant 中所有元素的长度。您会看到其中一个的长度为零。

In [13]: [len(i) for i in variant]
Out[13]: [3, 4, 2, 2, 2, 0, 22, 9, 1]

应该从您的输入中删除这个空列表。 itertools.product 从其每个输出值的每个参数中获取一个元素,因此任何空列表都将导致它不返回任何结果。

相关问题