from itertools import product
a = "abcd"
A = "ABCD"
print [[a[y] if x[y] else A[y] for y in range(len(x))] \
for x in product(range(2), repeat=4)]
编辑:另一种方法:
^{pr2}$
编辑2:任意数量列表的通用解决方案:
def sublist(*lists):
if not len(set(len(x) for x in lists)) == 1:
raise ValueError("Lists must all be the same length")
length = len(lists[0])
return [[lists[y][i] for i, y in enumerate(x)] \
for x in product(range(len(lists)), repeat=length)]
print sublist("ab", "AB", "12")
# [['a', 'b'], ['a', 'B'], ['a', '2'], ['A', 'b'], ['A', 'B'], ['A', '2'], ['1', 'b'], ['1', 'B'], ['1', '2']]
list1 = ['a', 'b', 'c', 'd']
list2 = ['A', 'B', 'C', 'D']
for i in xrange(2**len(list1)):
output = []
for j in xrange(0, len(list1)):
bit = i & (1 << j)
if bit == 0:
output.append(list1[j])
else:
output.append(list2[j])
print output
递归是你的朋友:
或者,如果你喜欢发电机:
^{pr2}$我有种感觉可以做得更好,但这至少可以:
编辑:另一种方法:
^{pr2}$编辑2:任意数量列表的通用解决方案:
相关问题 更多 >
编程相关推荐