[python] 객체 목록 섞기

객체 목록이 있고 섞고 싶습니다. 나는이 random.shuffle방법을 사용할 수 있다고 생각 했지만 목록이 객체 일 때 실패하는 것 같습니다. 객체를 섞는 방법이 나이 주위에 다른 방법이 있습니까?

import random

class A:
    foo = "bar"

a1 = a()
a2 = a()
b = [a1, a2]

print(random.shuffle(b))

실패합니다.



답변

random.shuffle작동해야합니다. 다음은 객체가 목록 인 예입니다.

from random import shuffle
x = [[i] for i in range(10)]
shuffle(x)

# print(x)  gives  [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]]
# of course your results will vary

셔플은 제자리 에서 작동 하며 없음을 반환합니다.


답변

내부 셔플 링을 배운대로 문제가 발생했습니다. 나는 또한 자주 문제가 있으며 종종 목록을 복사하는 방법을 잊어 버리는 것 같습니다. 사용 sample(a, len(a))len(a)표본 크기로 사용하는 솔루션 입니다. Python 설명서는 https://docs.python.org/3.6/library/random.html#random.sample 을 참조 하십시오 .

다음 random.sample()은 섞은 결과를 새 목록으로 반환 하는 간단한 버전 입니다.

import random

a = range(5)
b = random.sample(a, len(a))
print a, b, "two list same:", a == b
# print: [0, 1, 2, 3, 4] [2, 1, 3, 4, 0] two list same: False

# The function sample allows no duplicates.
# Result can be smaller but not larger than the input.
a = range(555)
b = random.sample(a, len(a))
print "no duplicates:", a == list(set(b))

try:
    random.sample(a, len(a) + 1)
except ValueError as e:
    print "Nope!", e

# print: no duplicates: True
# print: Nope! sample larger than population


답변

그것을 얻는 데 시간이 걸렸습니다. 그러나 셔플에 대한 문서는 매우 명확합니다.

목록 x 를 섞으십시오 . None을 반환합니다.

따라서해서는 안됩니다 print(random.shuffle(b)). 대신 할 random.shuffle(b)다음과 print(b).


답변

#!/usr/bin/python3

import random

s=list(range(5))
random.shuffle(s) # << shuffle before print or assignment
print(s)

# print: [2, 4, 1, 3, 0]


답변

이미 numpy를 사용하고 있다면 (과학 및 금융 응용 프로그램에 매우 인기가 있음) 수입을 절약 할 수 있습니다.

import numpy as np    
np.random.shuffle(b)
print(b)

http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.shuffle.html


답변

>>> import random
>>> a = ['hi','world','cat','dog']
>>> random.shuffle(a,random.random)
>>> a
['hi', 'cat', 'dog', 'world']

그것은 나를 위해 잘 작동합니다. 무작위 방법을 설정하십시오.


답변

목록이 여러 개인 경우 순열을 정의하고 (목록을 섞거나 목록의 항목을 다시 정렬하는 방법) 먼저 모든 목록에 적용 할 수 있습니다.

import random

perm = list(range(len(list_one)))
random.shuffle(perm)
list_one = [list_one[index] for index in perm]
list_two = [list_two[index] for index in perm]

너피 /시피

목록이 numpy 배열이면 더 간단합니다.

import numpy as np

perm = np.random.permutation(len(list_one))
list_one = list_one[perm]
list_two = list_two[perm]

mpu

함수 mpu가있는 작은 유틸리티 패키지 를 만들었습니다 consistent_shuffle.

import mpu

# Necessary if you want consistent results
import random
random.seed(8)

# Define example lists
list_one = [1,2,3]
list_two = ['a', 'b', 'c']

# Call the function
list_one, list_two = mpu.consistent_shuffle(list_one, list_two)

참고 mpu.consistent_shuffle인수의 임의의 수를합니다. 따라서 세 개 이상의 목록을 섞을 수도 있습니다.