我有一个这样的列表。
l_of_l = [[1,2,3], [4,5],[6]]
我想随机替换两个元素的交叉列表,例如:
perm(l_of_l) = [[1, 4, 3], [2, 5], [6]] # 2 and 4 replaced
perm(l_of_l) = [[6, 2, 3], [4, 5], [1]] # 6 and 1 replaced
#etc.
列表的长度应该被保存下来,而同一列表的替换则被拒绝。
perm(l_of_l) = [[1, 2], [4, 5], [3, 6]] # illegal permutation - the lenght of lists changed
perm(l_of_l) = [[2, 1, 3], [4, 5], [6]] # illegal permutation - 1 and 2 are from the same list
我已经尝试使用itertools.permutaion,但它不工作。
# permutations using library function
from itertools import permutations
# Get all permutations of lists
perm = permutations([[1, 2, 3], [4, 5], [6]])
# Print the obtained permutations
for i in list(perm):
print (i)
#output:
#([1, 2, 3], [4, 5], [6])
#([1, 2, 3], [6], [4, 5])
#([4, 5], [1, 2, 3], [6])
#([4, 5], [6], [1, 2, 3])
#([6], [1, 2, 3], [4, 5])
#([6], [4, 5], [1, 2, 3])
你对我有什么建议?
先谢谢你
这是一个天真的解决方案,为了清晰起见,分成几行。
l_of_l = [[1,2,3], [4,5],[6]]
num_lists = len(l_of_l)
l1_inx, l2_inx = random.sample(range(num_lists), 2)
len1 = len(l_of_l[l1_inx])
len2 = len(l_of_l[l2_inx])
elem1 = random.randint(0, len1-1)
elem2 = random.randint(0, len2-1)
temp = l_of_l[l1_inx][elem1]
l_of_l[l1_inx][elem1] = l_of_l[l2_inx][elem2]
l_of_l[l2_inx][elem2] = temp