개체 목록 섞기
오브젝트 목록을 어떻게 셔플합니까?시도했습니다.
import random
b = [object(), object()]
print(random.shuffle(b))
하지만 출력은 다음과 같습니다.
None
random.shuffle
작동해야 합니다.다음은 오브젝트가 목록인 예를 제시하겠습니다.
from random import shuffle
x = [[i] for i in range(10)]
shuffle(x)
print(x)
# print(x) gives [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]]
주의:shuffle
제자리걸음으로 되돌아가다None
.
더 일반적으로 Python에서는 가변 객체가 함수로 전달될 수 있으며 함수가 이러한 객체를 변환하면 표준이 반환됩니다.None
(예를 들어 변이된 객체가 아니라)
아시다시피 사내에서 셔플을 하는 것이 문제였습니다.저도 자주 문제가 있어서 목록 복사하는 법을 잊어버리는 경우가 많은 것 같아요.사용.sample(a, len(a))
이 솔루션은len(a)
샘플 사이즈로 합니다.Python 의 메뉴얼에 대해서는, https://docs.python.org/3.6/library/random.html#random.sample 를 참조해 주세요.
여기 간단한 버전이 있습니다.random.sample()
shuffed 결과를 새 목록으로 반환합니다.
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를 제자리에 섞습니다.
실행 안 함:
print(random.shuffle(xs)) # WRONG!
대신 다음 작업을 수행합니다.
random.shuffle(xs)
print(xs)
#!/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]
(과학 및 재무 애플리케이션용 인기 라이브러리)의 경우 다음을 사용합니다.
import numpy as np
b = np.arange(10)
np.random.shuffle(b)
print(b)
>>> 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 / 스키피
목록이 numpy 배열인 경우 다음과 같이 간단합니다.
import numpy as np
perm = np.random.permutation(len(list_one))
list_one = list_one[perm]
list_two = list_two[perm]
mpu
다음과 같은 기능을 가진 작은 유틸리티 패키지를 만들었습니다.
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
는 임의의 수의 인수를 사용합니다.따라서 3개 이상의 목록을 섞을 수도 있습니다.
1 행의 경우는,random.sample(list_to_be_shuffled, length_of_the_list)
예를 들어 다음과 같습니다.
import random
random.sample(list(range(10)), 10)
출력: [2, 9, 7, 8, 3, 0, 4, 1, 6, 5]
from random import random
my_list = range(10)
shuffled_list = sorted(my_list, key=lambda x: random())
이 대체 방법은 주문 기능을 스왑하는 일부 응용 프로그램에 유용할 수 있습니다.
경우에 따라 numpy 어레이를 사용하는 경우random.shuffle
어레이에 중복 데이터가 생성되었습니다.
다른 방법으로는numpy.random.shuffle
이미 numpy를 사용하고 있다면 일반적인 방법보다 이 방법을 사용하는 것이 좋습니다.random.shuffle
.
예
>>> import numpy as np
>>> import random
사용.random.shuffle
:
>>> foo = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> foo
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> random.shuffle(foo)
>>> foo
array([[1, 2, 3],
[1, 2, 3],
[4, 5, 6]])
사용.numpy.random.shuffle
:
>>> foo = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> foo
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> np.random.shuffle(foo)
>>> foo
array([[1, 2, 3],
[7, 8, 9],
[4, 5, 6]])
print func(foo)는 foo와 함께 호출할 때 func의 반환값을 인쇄합니다.그러나 'shuffle'에는 반환 유형으로 None이 있습니다.목록이 수정되기 때문에 아무것도 인쇄되지 않습니다.회피책:
# shuffle the list in place
random.shuffle(b)
# print it
print(b)
기능적인 프로그래밍 스타일에 더 관심이 있다면 다음과 같은 래퍼 기능을 만들 수 있습니다.
def myshuffle(ls):
random.shuffle(ls)
return ls
하다라는 할 수 .shuffled
로)sort
»sorted
)
def shuffled(x):
import random
y = x[:]
random.shuffle(y)
return y
x = shuffled([1, 2, 3, 4])
print x
import random
class a:
foo = "bar"
a1 = a()
a2 = a()
a3 = a()
a4 = a()
b = [a1,a2,a3,a4]
random.shuffle(b)
print(b)
shuffle
.None
, , , , , , , , , , , , , , , , , , , , , , , , , .
shuffle 또는 sample을 사용할 수 있습니다. 둘 다 랜덤 모듈에서 가져온 것입니다.
import random
def shuffle(arr1):
n=len(arr1)
b=random.sample(arr1,n)
return b
또는
import random
def shuffle(arr1):
random.shuffle(arr1)
return arr1
소스 파일의 이름을 random.py로 지정하지 않았는지, 작업 디렉토리에 random.pyc라는 파일이 없는지 확인하십시오.또는 프로그램이 로컬 랜덤 가져오기를 시도할 수 있습니다.py 파일을 만듭니다.
다음과 같이 할 수 있습니다.
>>> A = ['r','a','n','d','o','m']
>>> B = [1,2,3,4,5,6]
>>> import random
>>> random.sample(A+B, len(A+B))
[3, 'r', 4, 'n', 6, 5, 'm', 2, 1, 'a', 'o', 'd']
두 개의 목록으로 돌아가려면 이 긴 목록을 두 개로 분할합니다.
def shuffle(_list):
if not _list == []:
import random
list2 = []
while _list != []:
card = random.choice(_list)
_list.remove(card)
list2.append(card)
while list2 != []:
card1 = list2[0]
list2.remove(card1)
_list.append(card1)
return _list
목록을 매개 변수로 사용하고 혼합된 버전의 목록을 반환하는 함수를 만들 수 있습니다.
from random import *
def listshuffler(inputlist):
for i in range(len(inputlist)):
swap = randint(0,len(inputlist)-1)
temp = inputlist[swap]
inputlist[swap] = inputlist[i]
inputlist[i] = temp
return inputlist
""" to shuffle random, set random= True """
def shuffle(x,random=False):
shuffled = []
ma = x
if random == True:
rando = [ma[i] for i in np.random.randint(0,len(ma),len(ma))]
return rando
if random == False:
for i in range(len(ma)):
ave = len(ma)//3
if i < ave:
shuffled.append(ma[i+ave])
else:
shuffled.append(ma[i-ave])
return shuffled
import random
class a:
foo = "bar"
a1 = a()
a2 = a()
b = [a1.foo,a2.foo]
random.shuffle(b)
이 스니펫은, 인플레이스 쉐이핑과 시드 조작 기능이 필요한 경우에 도움이 됩니다.
from random import randint
a = ['hi','world','cat','dog']
print(sorted(a, key=lambda _: randint(0, 1)))
"shuffling"은 임의 키별로 정렬하는 것입니다.
Shuffling 프로세스는 "교체 포함"이기 때문에 각 아이템의 발생이 변경될 수 있습니다!적어도 목록에 있는 항목도 목록에 있는 경우.
예.,
ml = [[0], [1]] * 10
끝나고,
random.shuffle(ml)
[0]의 숫자는 9 또는 8일 수 있지만 정확히 10은 아닙니다.
계획: 무거운 것을 들어 올리기 위해 도서관에 의존하지 않고 셔플을 작성합니다.예: 0번 요소부터 시작하여 목록을 처음부터 살펴봅니다. 예를 들어, 6번 요소의 새로운 랜덤 위치를 찾아 6번 요소의 값에 0을 넣고 6번 요소의 값은 0번입니다.요소 1로 이동하여 목록의 나머지 부분까지 이 프로세스를 반복합니다.
import random
iteration = random.randint(2, 100)
temp_var = 0
while iteration > 0:
for i in range(1, len(my_list)): # have to use range with len()
for j in range(1, len(my_list) - i):
# Using temp_var as my place holder so I don't lose values
temp_var = my_list[i]
my_list[i] = my_list[j]
my_list[j] = temp_var
iteration -= 1
하시면 됩니다.random.choices()
록을섞섞 섞섞섞다다
TEAMS = [A,B,C,D,E,F,G,H]
random.choices(TEAMS,k = len(TEAMS))
위의 코드는 이전 목록과 같은 길이의 임의 목록을 반환합니다.
도움이 되길 바랍니다!!!
잘 되고 있어요.리스트 오브젝트로서 기능하고 있습니다.
from random import shuffle
def foo1():
print "foo1",
def foo2():
print "foo2",
def foo3():
print "foo3",
A=[foo1,foo2,foo3]
for x in A:
x()
print "\r"
shuffle(A)
for y in A:
y()
foo1 foo2 foo3 foo2 foo3 foo1 (마지막 줄에 있는 foo는 랜덤 순서로 되어 있습니다)
언급URL : https://stackoverflow.com/questions/976882/shuffling-a-list-of-objects
'it-source' 카테고리의 다른 글
특수한 포인터Collectors.toMap에 null 엔트리 값이 있는 예외가 있습니다. (0) | 2022.11.20 |
---|---|
Gzip의 JavaScript 구현 (0) | 2022.11.20 |
MySql 최대 메모리 용량이 위험할 정도로 높아도 증대가 필요함 (0) | 2022.11.19 |
bind_result vs get_result를 사용하는 방법의 예 (0) | 2022.11.19 |
regex의 "\d"는 숫자를 의미합니까? (0) | 2022.11.19 |