我们有两个集合,
A = ['dog', 'cat']
B = ['run', 'walk']
我们期望得到的结果为:
Result = ['dog_run', 'dog_walk', 'cat_run', 'cat_walk']
并且集合数量不固定的话,我们应该用树节点法解决这个问题,代码如下:
result = []
groups = [['dog', 'cat'], ['walk', 'run']]
for group in groups:
if len(result) is 0:
result = group
else:
new_result = []
for item in group:
for previous_item in result:
new_result.append(previous_item + '_' + item)
result = new_result
print(result)
当然,这个是算法,如果使用的语言自身带有库的话也可以写更简单点,比如Python:
from itertools import product
groups = [set(['dog', 'cat']), set(['walk', 'run'])]
result = groups[0]
for index in range(1, len(groups)):
result = product(result, groups[index])
for item in result:
print('_'.join(item))