/ / Python tasuje zawartość podlisty listy - python, list, losowe, shuffle, listy zagnieżdżone

Python tasuje zawartość podlisty listy - python, lista, losowe, losowe, zagnieżdżone listy

Mam listę list w python: l = [ [1,2,3], [4,5,6], [7,8,9] ] i chcę przetasować każdą podlistę. Jak mogę to osiągnąć?

Zwróć uwagę, że kolejność podlist musi być zachowana, podczas gdy ich zawartość jest tasowana. Różni się to od poprzednich pytań, takich jak to pytanie, w którym następuje przetasowanie zamówienia i zachowanie zawartości.

Próbowałem następujące:

import random

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

random.shuffle(x) # This shuffles the order of the sublists,
# not the sublists themselves.

x = [ random.shuffle(sublist) for sublist in x ] # This returns None
# for each sublist.

print(x)

Odpowiedzi:

2 dla odpowiedzi № 1

Nie potrzebujesz "x =" w czwartej linii.

Kod:

import random

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

random.shuffle(x) # This shuffles the order of the sublists,
# not the sublists themselves.

[ random.shuffle(sublist) for sublist in x ] # This returns None
# for each sublist.

print(x)

Po sugestii w komentarzu, jest to nowsza wersja:

import random
x = [ [1,2,3], [4,5,6], [7,8,9] ]
random.shuffle(x)
for sublist in x:
random.shuffle(sublist)
print(x)

1 dla odpowiedzi nr 2

shuffle działa w miejscu i nic nie zwraca, więc użyj:

random.shuffle(x)
for i in x:
random.shuffle(i)
print(x)

-1 dla odpowiedzi nr 3

Możesz wypróbować inną funkcję o nazwie tak jak ta. Używam Pythona 3.6.

z losowego importu * x = [sample (i, len (i)) dla i in x] shuffle (x)

to bardzo łatwe! Chociaż łatwo jest go rozwiązać, możesz wypróbować inną funkcję.