簡體   English   中英

Python中字典中元素的組合

[英]Combinations of elements in a dict in python

假設我有以下形式的有序字典

d = OrderedDict([('x1', ['x1_0', 'x1_1']), ('x2', ['x2_0', 'x2_1','x2_2'])])

如何獲得表格的組合

[('x1_0', 'x2_0'),('x1_0', 'x2_1'),('x1_0', 'x2_2'),('x1_1', 'x2_0'),('x1_1', 'x2_1'),('x1_1', 'x2_2')]

PS在這里,我只顯示兩個變量的結果,但是我在尋找更通用的代碼。 還可以隨意使用盡可能多的工具...

看起來你想要類似的東西

import itertools
x = list(itertools.product(*d.values()))

這遺漏了您想要的東西嗎?

我嘗試了以下方法:

import collections
from itertools import product
d = collections.OrderedDict([('x1', ['x1_0', 'x1_1']), ('x2', ['x2_0',     'x2_1','x2_2'])])
poss = [(k,v) if v else (k,) for k,v in d.items()]
list(product(*poss))

輸出:

 [('x1', 'x2'),
 ('x1', ['x2_0', 'x2_1', 'x2_2']),
 (['x1_0', 'x1_1'], 'x2'),
 (['x1_0', 'x1_1'], ['x2_0', 'x2_1', 'x2_2'])]

它給了我一個組合,而不是完全按照您的示例形式,但是如果有人需要其他組合,它就給了我一個組合。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM