我的清单:
a = [1,2,3]
我想要的输出:
combinations = [11, 12, 13, 21, 22, 23, 31, 32, 33]
我试过了:
a = [1,2,3]
all_combinations = []
list1_permutations = itertools.permutations(a, len(a))
for each_permutation in list1_permutations:
zipped = zip(each_permutation, a)
all_combinations.append(list(zipped))
print(all_combinations)
但是我得到的输出如下:
[[(1, 1), (2, 2), (3, 3)], [(1, 1), (3, 2), (2, 3)], [(2, 1), (1, 2), (3, 3)], [(2, 1), (3, 2), (1, 3)], [(3, 1), (1, 2), (2, 3)], [(3, 1), (2, 2), (1, 3)]]
使用嵌套列表推导,这可能是最简单的:
a = [1, 2, 3]
out = [int(f'{i}{j}') for i in a for j in a]
print(out)
输出:
[11, 12, 13, 21, 22, 23, 31, 32, 33]
使用以下命令可以达到相同的结果(也许更有效)itertools.product
:
import itertools
a = [1, 2, 3]
out = [int(f"{a}{b}") for a, b in itertools.product(a, a)]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句