슬슬 객체의 목록

I have a list 객체와 난 로렌아줌마가 섞으려면 저들이요 하지만 이 방법을 사용할 수 있습니다 '란도메이휴슈플 생각해봤죠 난' 때 객체의 목록은 실패할 것으로 보인다. 객체 또는 다른 방법으로 이 주위에 슬슬 방법 있나요?

import random

class A:
    foo = "bar"

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

print(random.shuffle(b))

이 실패합니다.

질문에 대한 의견 (8)
해결책

['란도메이휴슈플'] [1] 노력해야 합니다. 예를 들면 here& # 39 에 있는 개체는 목록:

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

참고로 무순서 작동됨 및 되돌려줍니다 자리에 없음.

[1]: https://docs.python.org/library/random.html # 란도메이휴슈플

해설 (8)

현재 위치 등 학습했습니다 슬슬 문제입니다. 난 또 얼마나 자주, 그리고 종종 잊을 수 있는 문제, 고쳐주렴 바뀌엇어요 복제본에 것으로 보인다. 사용 예제 (a, 렌 (a)) '가', '렌 (a)' 를 통해 솔루션 샘플 크기. # 란도메이휴샘프러 (https://docs.python.org/3.6/library/random.html) 를 파이썬 문서 참조.

39 의 here& 간단한 버전으로 란도메이휴샘프러 () '에서' 로 인해 새로운 목록을 되돌려줍니다 단행했다.

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
해설 (4)

좀 너무 시간을 가질 수 있는 시간이 걸렸다. 그러나 설명서 무순서 아주 명확해집니다.

&gt. , 제자리에 x 무순서 목록 반품하십시오 없음.

그래서 니말은 shouldn& # 39, t '보기인쇄 (란도메이휴슈플 (b)'. '다음' 보기인쇄 (b) '대신' 실행하십시오 란도메이휴슈플 (b).

해설 (0)

#!/usr/bin/python3

import random

s=list(range(5))
random.shuffle(s) # 
해설 (0)

누마피 발생할 경우 이미 (매우 인기 있는 과학 및 금융 응용 프로그램을 사용할 수 있는 가져오기의 교도관님도요 저장할 수 있습니다.

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

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

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

작동하잖아 미세 for me. Smartupdate 무순서 설정하는 방법이다.

해설 (4)

여러 개 있을 경우 할 수 있습니다 열거합니다 정의하십시오 교환 (the way you 무순서 목록 / 재정렬할 목록에 있는 항목) 를 먼저 그리곤요 적용하십시오 모든 목록:

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]

누마피 / 스키피

이 경우 간단해진다는 열거합니다 누마피 어레이에는 있다.

import numpy as np

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

mpu

39, ve 창조하 i& 작은 유틸리티 패키지 ['mpu'] (https://github.com/MartinThoma/mpu) 이 있는 ['consistent_shuffle'] (http://mpu.readthedocs.io/en/latest/mpu.html # 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' 는 임의의 개수의 인수만. 그래서 이를 통해 3 개 이상의 열거합니다 무순서 수도 있습니다.

해설 (0)
from random import random
my_list = range(10)
shuffled_list = sorted(my_list, key=lambda x: random())

이 방법은 일부 애플리케이션에 유용할 수 있는 오더할 운영까지도 바꿀 수 있다.

해설 (2)

경우에 따라 '에서' 중복 데이터를 사용하여 만든 누마피 사용할 때 어레이에는 란도메이휴슈플 어레이입니다.

'대체' 누마피.란도메이휴슈플 사용할 수 있습니다. # 39 는 이미, 이 경우, re 작업할 수 있는 좋은 방법을 통해 you& 누마피 란도메이휴슈플 '일반'.

누마피.란도메이휴슈플

  • 예 *
>>> import numpy as np
>>> import random

'란도메이휴슈플 사용하여':

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

'누마피.란도메이휴슈플 사용하여':

>>> 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]])
해설 (5)

& # 39, & # 39 인쇄하십시오 func (foo). # 39, & # 39 는 반환 값 인쇄인쇄 func&. # 39, & # 39, foo& 함께 호출될 때.

39, & # 39 shuffle&. 그러나 그 곳에 복귀하십시오 형식 목록에 수정할 수 없 는 인쇄, 따라서 이는 아무것도아니야.

해결 방법:

# shuffle the list in place 
random.shuffle(b)

# print it
print(b)

39 에 더 많은 경우, re you& 함수형 프로그래밍 스타일을 만들 수 있습니다 다음 래퍼 기능:

def myshuffle(ls):
    random.shuffle(ls)
    return ls
해설 (2)

한 라이너 '를 사용하여 란도메이휴샘프러 (list_to_be_shuffled, length_of_the_list)' 을 (를) 예:

import random
random.sample(list(range(10)), 10)

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

해설 (0)

하나의 함수를 정의할 수 있습니다 '라는 셔플' ('vs' 의 '같은 감지에서 정렬하려면 정렬할지')

def shuffled(x):
    import random
    y = x[:]
    random.shuffle(y)
    return y

x = shuffled([1, 2, 3, 4])
print x
해설 (0)
import random

class a:
    foo = "bar"

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

random.shuffle(b)
print(b)

그 결과, '무순서 말라' 는 '없음' 이 마련되어 있으며, 하지만 명단요 인쇄하십시오.

해설 (0)

이를 위해 이동할 수 있습니다.

>>> 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']

그런 다음, 이 두 확인표시를 돌아가 열거합니다 분할합니다 긴 두 개의 목록으로.

해설 (0)
""" 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
해설 (4)

또는 샘플링합니다 무순서 사용할 수 있습니다. 모두 재배케하여 come from 임의적입니까 모듈에서는.

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
해설 (0)

어떤 함수의 매개 변수로 및 되돌려줍니다 바뀌엇어요 넘겨받은 만들 수 있습니다 한 셔플 버전의 목록:

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
해설 (0)
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
해설 (5)

You are not smartupdate 소스 파일 이름 지정 및 파일 작업 디렉토리에 란도마리피충 불렀으매 없다고 random.py 대신 해당 지역 random.py 파일 및 가져오기할 좋아하는 프로그램 중 발생할 수 있다고 시도하시려면 무순서 모듈에서는 비단뱀.

해설 (0)
import random
class a:
    foo = "bar"

a1 = a()
a2 = a()
b = [a1.foo,a2.foo]
random.shuffle(b)
해설 (0)