Python 3.x 在python中查找列表的所有组合
我的名单如下:Python 3.x 在python中查找列表的所有组合,python-3.x,list,Python 3.x,List,我的名单如下: 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_permutat
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]
同样的结果可以通过以下方式更有效地实现:
使用嵌套列表理解可能最简单:
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]
同样的结果可以通过以下方式更有效地实现:
这应该行得通
您可以使用列表理解来创建所有组合,因为您似乎希望使用类似“33”的重复项进行采样
您可以使用列表生成器来执行此操作
您需要将这些项视为字符串来连接它们
如果这是您想要的最终结果,您需要将其转换回整数
这应该行得通
您可以使用列表理解来创建所有组合,因为您似乎希望使用类似“33”的重复项进行采样
您可以使用列表生成器来执行此操作
您需要将这些项视为字符串来连接它们
如果这是您想要的最终结果,您需要将其转换回整数
谢谢你,我们怎样才能从中获得唯一的价值?谢谢你的帮助谢谢你,我们怎样才能从中获得唯一的价值?谢谢你的帮助