📜  在Python中打乱数组

📅  最后修改于: 2022-05-13 01:55:27.759000             🧑  作者: Mango

在Python中打乱数组

打乱数字序列一直是一个有用的工具,它只不过是重新排列数组中的元素。知道不止一种方法来实现这一点总是一个加分项。让我们讨论实现这一目标的某些方法。

方法一:在这个方法中我们使用shuffle() 来自numpy库的方法。

Python3
# Import required module
import numpy as np
 
# Assign array
arr = np.array([1, 2, 3, 4, 5, 6])
 
# Display original array
print("Original array: ", arr)
 
# Shuffle array
np.random.shuffle(arr)
 
# Display shuffled array
print("Shuffled array: ", arr)


Python3
# Import required module
import random
import array
 
# Assign array
arr = np.array([1, 2, 3, 4, 5, 6])
 
# Display original array
print("Original array: ", arr)
 
# Shuffle array
random.shuffle(arr)
 
# Display shuffled array
print("Shuffled array: ", arr)


Python3
# Import required module
import random
import array
 
# Assign array
# here q indicates that the array
# contains signed integer
arr = array.array('q', [1, 2, 3, 4, 5, 6])
 
# Display original array
print("Original array: ", arr)
 
# Shuffle array
# Here sample() returns a list, so we
# are typecasting list into array
arr = array.array('q', random.sample(list(arr), 6))
 
# Display shuffled array
print("Shuffled array: ", arr)


Python3
# Import required module
import random
import array
 
 
 
# Create class to shuffle array
class Shuffler(object):
 
    # Constructor
    def __init__(self, arr):
 
        # Initializes the temp_array
        self.temp_array = arr
 
        # All the indices are stored in indices list
        self.indices = [index for index in range(len(arr))]
 
    # method to shuffle array
    def shuffle(self):
 
        # if length of array is zero empty array is returned.
        if not len(self.temp_array):
            return []
 
        # The below swapping process is repeated randomly in range of
        # half of length of array to length of the array, in this case,
        # it is repeated randomly in between 3 to 6 times.
        for i in range(random.randint(int(len(self.temp_array)/2), len(self.temp_array))):
 
            # randomly choses two indices that is i, j from indices list
            i = random.choice(self.indices)
            j = random.choice(self.indices)
 
            # swapping the elements present at i,j indices.
            self.temp_array[i], self.temp_array[j] = self.temp_array[j], self.temp_array[i]
        return self.temp_array
 
 
 
# Driver code
 
# Assign array
arr = array.array('q', [1, 2, 3, 4, 5, 6])
 
# Create Object of Shuffler class
ob = Shuffler(arr)
 
# Display original array
print("Original array: ", arr)
 
# Shuffle method is called
print("Shuffled array: ", ob.shuffle())


Python3
# Import required module
import random
import numpy as np
 
 
# A function to generate a random
# permutation of array
def shuffler (arr, n):
     
    # We will Start from the last element
    # and swap one by one.
    for i in range(n-1,0,-1):
         
        # Pick a random index from 0 to i
        j = random.randint(0,i+1)
         
        # Swap arr[i] with the element at random index
        arr[i],arr[j] = arr[j],arr[i]
    return arr
 
   
   
# Driver code
     
# Assign array
arr = np.array([1, 2, 3, 4, 5, 6])
 
# Display original array
print("Original array: ",arr)
 
# Get length of array
n = len(arr)
 
# Use shuffler() function to get shuffled array
print("Shuffled array: ",shuffler(arr, n))


Python3
import random
 
arr=[1,2,3,4,5,6]
n=len(arr)-1
for i in range(n):
    random_index = random.randint(0, n)
    temp = arr.pop(random_index)
    arr.append(temp)
print(arr)


输出

Original array:  [1 2 3 4 5 6]
Shuffled array:  [4 1 5 3 2 6]

方法 2:在此方法中,我们将使用Random库中的shuffle()方法对给定数组进行打乱。

蟒蛇3

# Import required module
import random
import array
 
# Assign array
arr = np.array([1, 2, 3, 4, 5, 6])
 
# Display original array
print("Original array: ", arr)
 
# Shuffle array
random.shuffle(arr)
 
# Display shuffled array
print("Shuffled array: ", arr)

输出:

Original array:  [1 2 3 4 5 6]
Shuffled array:  [4 5 2 6 1 3]

方法 3:在此方法中,我们将使用Random库中的sample()方法对给定数组进行打乱。

蟒蛇3

# Import required module
import random
import array
 
# Assign array
# here q indicates that the array
# contains signed integer
arr = array.array('q', [1, 2, 3, 4, 5, 6])
 
# Display original array
print("Original array: ", arr)
 
# Shuffle array
# Here sample() returns a list, so we
# are typecasting list into array
arr = array.array('q', random.sample(list(arr), 6))
 
# Display shuffled array
print("Shuffled array: ", arr)

输出:

Original array:  array('q', [1, 2, 3, 4, 5, 6])
Shuffled array:  array('q', [6, 3, 2, 1, 5, 4])

方法 4:在这种方法中,我们将随机选择 2 个索引,然后交换它们。这个过程将随机重复最多 n/2 到 n 次,其中 n 是数组的长度。

蟒蛇3

# Import required module
import random
import array
 
 
 
# Create class to shuffle array
class Shuffler(object):
 
    # Constructor
    def __init__(self, arr):
 
        # Initializes the temp_array
        self.temp_array = arr
 
        # All the indices are stored in indices list
        self.indices = [index for index in range(len(arr))]
 
    # method to shuffle array
    def shuffle(self):
 
        # if length of array is zero empty array is returned.
        if not len(self.temp_array):
            return []
 
        # The below swapping process is repeated randomly in range of
        # half of length of array to length of the array, in this case,
        # it is repeated randomly in between 3 to 6 times.
        for i in range(random.randint(int(len(self.temp_array)/2), len(self.temp_array))):
 
            # randomly choses two indices that is i, j from indices list
            i = random.choice(self.indices)
            j = random.choice(self.indices)
 
            # swapping the elements present at i,j indices.
            self.temp_array[i], self.temp_array[j] = self.temp_array[j], self.temp_array[i]
        return self.temp_array
 
 
 
# Driver code
 
# Assign array
arr = array.array('q', [1, 2, 3, 4, 5, 6])
 
# Create Object of Shuffler class
ob = Shuffler(arr)
 
# Display original array
print("Original array: ", arr)
 
# Shuffle method is called
print("Shuffled array: ", ob.shuffle())

输出:

Original array:  array('q', [1, 2, 3, 4, 5, 6])
Shuffled array:  array('q', [1, 6, 3, 2, 4, 5])

方法5:这是最有效的方法之一,它是Fisher-Yates shuffle Algorithm。下面的程序将帮助您理解这个算法。

蟒蛇3

# Import required module
import random
import numpy as np
 
 
# A function to generate a random
# permutation of array
def shuffler (arr, n):
     
    # We will Start from the last element
    # and swap one by one.
    for i in range(n-1,0,-1):
         
        # Pick a random index from 0 to i
        j = random.randint(0,i+1)
         
        # Swap arr[i] with the element at random index
        arr[i],arr[j] = arr[j],arr[i]
    return arr
 
   
   
# Driver code
     
# Assign array
arr = np.array([1, 2, 3, 4, 5, 6])
 
# Display original array
print("Original array: ",arr)
 
# Get length of array
n = len(arr)
 
# Use shuffler() function to get shuffled array
print("Shuffled array: ",shuffler(arr, n))

输出:

Original array:  [1 2 3 4 5 6]
Shuffled array:  [6 1 2 3 4 5]

方法六:

在这种方法中,我们将随机选择一个索引并将其附加到数组的末尾。这将重复 n 次,其中 n 是数组的长度。

蟒蛇3

import random
 
arr=[1,2,3,4,5,6]
n=len(arr)-1
for i in range(n):
    random_index = random.randint(0, n)
    temp = arr.pop(random_index)
    arr.append(temp)
print(arr)
输出
[2, 3, 6, 1, 5, 4]