programing tip

개체 목록 섞기

itbloger 2020. 9. 30. 08:54
반응형

개체 목록 섞기


파이썬에 객체 목록이 있고 그것들을 섞고 싶습니다. 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

shuffle 이 제자리 에서 작동 하고 None을 반환합니다.


제자리 셔플이 문제라는 것을 알았을 때. 나도 자주 문제가 생기고 목록을 복사하는 방법도 잊는 것 같습니다. 사용 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 in place ; 없음을 반환합니다.

그래서 당신은해서는 안됩니다 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 / Scipy

목록이 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인수의 임의의 수를합니다. 따라서 세 개 이상의 목록을 섞을 수도 있습니다.


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.

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

한 줄짜리의 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]


하나는 shuffled( sortvs 와 같은 의미로 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목록입니다.


이것을 위해 갈 수 있습니다.

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

두 목록으로 돌아가려면이 긴 목록을 두 개로 나눕니다.


목록을 매개 변수로 사용하고 목록의 섞인 버전을 반환하는 함수를 만들 수 있습니다.

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

you can either use shuffle or sample . both of which come from random module.

import random
def shuffle(arr1):
    n=len(arr1)
    b=random.sample(arr1,n)
    return b

OR

import random
def shuffle(arr1):
    random.shuffle(arr1)
    return arr1

Make sure you are not naming your source file random.py, and that there is not a file in your working directory called random.pyc.. either could cause your program to try and import your local random.py file instead of pythons random module.


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

import random
class a:
    foo = "bar"

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

The shuffling process is "with replacement", so the occurrence of each item may change! At least when when items in your list is also list.

E.g.,

ml = [[0], [1]] * 10

After,

random.shuffle(ml)

The number of [0] may be 9 or 8, but not exactly 10.


Plan: Write out the shuffle without relying on a library to do the heavy lifting. Example: Go through the list from the beginning starting with element 0; find a new random position for it, say 6, put 0’s value in 6 and 6’s value in 0. Move on to element 1 and repeat this process, and so on through the rest of the list

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

It works fine. I am trying it here with functions as list objects:

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

It prints out: foo1 foo2 foo3 foo2 foo3 foo1 (the foos in the last row have a random order)

참고URL : https://stackoverflow.com/questions/976882/shuffling-a-list-of-objects

반응형