我也使用了itertools和for循环,但我不确定有超过2个键的模式是什么,与itertools一样,对于3个键,我从每个对应的键中获得一个列表元素,
d = {‘1’: ['a','b'], '2':['c','d'], '3' : ['m']}
output : acm adm bcm bdm
或者输出应该是:ac ad am bc bd bm cm dm
问:编写一个Python程序来创建和显示所有字母的组合,从字典中的不同键中选择每个字母。
Sample data: {‘1’: ['a','b'], '2':['c','d']}
expected Output:
ac
ad
bc
bd
我的代码:
dic = { '1' : ['a', 'b', '8'], '2' : ['c', 'd', 'm']}
i = 0;
key1 = list(dic.keys())[0]
key2 = list(dic.keys())[1]
for i in range(len(dic[key1])):
for j in range(len(dic[key2])):
print(dic[key1][i], end = "")
print(dic[key2][j])
输出: -
ac ad am bc bd bm 8c 8d 8m
如果您想使用itertools组合,在您的示例中,您应该探索如下内容:
from itertools import combinations
dic1 = ['a', 'b', '8']
dic2 = ['c', 'd', 'm']
for i in dic1:
for j in dic2:
for k in combinations(i+j,2):
print(k)
如果你想要推断出3个列表,你应该这样做:
from itertools import combinations
dic1 = ['a', 'b']
dic2 = ['c', 'd']
dic3 = ['m']
for i in (dic1):
for j in dic2:
for k in dic3:
for l in combinations(i+j+k,3):
print(l)
由于我不完全理解你的期望是什么,对于你的例子的最后一种可能性,以下是你应该为3个列表中的2个组合做的事情:
from itertools import combinations
dic1 = ['a', 'b']
dic2 = ['c', 'd']
dic3 = ['m']
for i in (dic1):
for j in dic2:
for k in dic3:
for l in combinations(i+j+k,2):
print(l)
这段代码没有针对高性能进行优化,但是从itertools
中理解组合的行为是很容易的。您可以使用itertools.combinations
和itertools.product
的混合
from itertools import combinations, product
d = {'1': ['a','b'], '2':['c','d'], '3' : ['m']}
[''.join(p) for c in combinations(d.values(), 2) for p in product(*c)]
# ['ac', 'ad', 'bc', 'bd', 'am', 'bm', 'cm', 'dm']