Python Matrix Random Mix Question.

Asked 1 years ago, Updated 1 years ago, 75 views

import random
A = [[0, 1, 2, 3, 4, 5],
     [1, 0, 3, 4, 5, 6],
     [2, 3, 0, 5, 6, 7],
     [3, 4, 5, 0, 7, 8],
     [4, 5, 6, 7, 0, 9],
     [5, 6, 7, 8, 9, 0]]

new_order = random.shuffle(A)
A[:] = [A[i] for i in new_order]
for row in A:
    row[:] = [row[i] for i in new_order]
    print row

I want to mix new_order randomly using shuffle like that, but I get an error like "TypeError: 'NoneType' object is not usable". What should I do?

python python-2.7

2022-09-22 11:43

2 Answers

import random
A = [[0, 1, 2, 3, 4, 5],
     [1, 0, 3, 4, 5, 6],
     [2, 3, 0, 5, 6, 7],
     [3, 4, 5, 0, 7, 8],
     [4, 5, 6, 7, 0, 9],
     [5, 6, 7, 8, 9, 0]]
map(random.shuffle, A)         # python 3 :list(map(random.shuffle, A))
print A                        # python 3: print(A)    


[[1, 2, 5, 4, 0, 3], [6, 3, 5, 1, 0, 4], [2, 3, 0, 7, 5, 6], [0, 4, 7, 3, 5, 8], [5, 6, 4, 0, 7, 9], [0, 5, 6, 8, 7, 9]]    
import random
from itertools import chain

A = [[0, 1, 2, 3, 4, 5],
     [1, 0, 3, 4, 5, 6],
     [2, 3, 0, 5, 6, 7],
     [3, 4, 5, 0, 7, 8],
     [4, 5, 6, 7, 0, 9],
     [5, 6, 7, 8, 9, 0]]

flattenA = list(chain(*A))
random.shuffle(flattenA)
print flattenA         # python 3: print(flattenA)

[6, 0, 0, 5, 5, 5, 9, 0, 4, 4, 8, 8, 3, 2, 6, 4, 9, 3, 5, 0, 4, 5, 2, 3, 1, 7, 3, 7, 1, 6, 0, 5, 0, 7, 7, 6]


2022-09-22 11:43

Remove 0 from the task list and insert 0 after the shuffle. In other words, insert zero into 0, 7, 14, 21, 28, 35.

You can do it as below.

import random
from itertools import chain

A = [[1, 2, 3, 4, 5],
     [1, 3, 4, 5, 6],
     [2, 3, 5, 6, 7],
     [3, 4, 5, 7, 8],
     [4, 5, 6, 7, 9],
     [5, 6, 7, 8, 9]]

flattenA = list(chain(*A))
random.shuffle(flattenA)
for i in (0, 7, 14, 21, 28, 35): flattenA.insert(i, 0)
print flattenA         # python 3: print(flattenA)


2022-09-22 11:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.