简体   繁体   中英

How to randomly replace elements between lists in list of lists

I have a list of lists like that:

l_of_l = [[1,2,3], [4,5],[6]]

and I want to replace two elements randomly cross-list, for example:

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.

The length of the list should be saved and replacement on the same list is declined.

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

I have been tried to use itertools.permutaion but it doesn't work:

# 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])

What do you suggest for me?

Thanks in advance!

Here's a naive solution, broken up into several lines for clarity:

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM