Python创建列表组合

时间:2016-09-07 16:16:46

标签: python combinations

我有一个包含元素和元素序列计数的字典。我想创建一个从这些元素组合的列表列表

实施例

Input: dictElement = {"PA":2,"PB":2}

Expected Output:
[('PB0', 'PA0'),
('PB0', 'PA1'),
('PB1', 'PA0'),
('PB1', 'PA1')]
Input: dictElement = {"PA":2,"PB":2,"PC":3}

Expected Output:
[('PC0', 'PB0', 'PA0'), 
('PC0', 'PB0', 'PA1'), 
('PC0', 'PB1', 'PA0'), 
('PC0', 'PB1', 'PA1'), 
('PC1', 'PB0', 'PA0'), 
('PC1', 'PB0', 'PA1'), 
('PC1', 'PB1', 'PA0'), 
('PC1', 'PB1', 'PA1'), 
('PC2', 'PB0', 'PA0'), 
('PC2', 'PB0', 'PA1'), 
('PC2', 'PB1', 'PA0'), 
('PC2', 'PB1', 'PA1')]

注意:字典的数字元素可以更改

1 个答案:

答案 0 :(得分:1)

您还没有指定应该在输出中处理字典键的顺序。如果假定反向排序顺序,您可以使用Private Sub Command223_Click() Dim ParID As Long Dim Combo As ComboBox Set Combo = Forms![Deal Tracker Query2]!Combo217 ParID = Me.ParentID.Value With Combo For i = 0 To Combo.ListCount - 1 If .Column(1, i) = ParID Then .Value = .ItemData(i) Exit For End If Next End With End Sub

轻松完成此操作
itertools.product()

演示:

from itertools import product

combinations = product(*(['{0}{1}'.format(v, i) for i in range(dictElement[v])] 
                         for v in sorted(dictElement, reverse=True))