杰瑞科技汇

python arrayshuffle

Of course! The term "array shuffle" in Python can mean a few different things depending on the context. I'll cover the three most common scenarios:

python arrayshuffle-图1
(图片来源网络,侵删)
  1. Shuffling a List (The most common case)
  2. Shuffling a NumPy Array
  3. Shuffling a multi-dimensional array (like a deck of cards)

Shuffling a Python List

The most direct way to shuffle a list in Python is by using the random.shuffle() function from the built-in random module.

Important Note: random.shuffle() shuffles the list in-place. This means it modifies the original list directly and does not return a new one.

Example:

import random
# Create a list of numbers
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("Original list:", my_list)
# Shuffle the list in-place
random.shuffle(my_list)
print("Shuffled list:", my_list)

Output:

Original list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Shuffled list: [4, 1, 8, 2, 10, 5, 9, 3, 7, 6] 
# (Your output will be different each time)

Getting a New Shuffled List (without modifying the original)

If you need to keep the original list intact and get a new, shuffled version, the best practice is to create a copy first and then shuffle the copy.

python arrayshuffle-图2
(图片来源网络,侵删)
import random
original_list = ['a', 'b', 'c', 'd', 'e']
# Create a copy of the list
shuffled_copy = original_list.copy()
# Shuffle the copy
random.shuffle(shuffled_copy)
print("Original list:", original_list)
print("Shuffled copy:", shuffled_copy)

Output:

Original list: ['a', 'b', 'c', 'd', 'e']
Shuffled copy: ['e', 'a', 'd', 'b', 'c']

Shuffling a NumPy Array

When working with numerical data, you'll likely be using NumPy. NumPy provides its own efficient shuffling functions.

Option A: numpy.random.shuffle() (In-place)

This works just like Python's random.shuffle(). It shuffles the array along its first axis.

import numpy as np
# Create a 1D NumPy array
my_array = np.array([10, 20, 30, 40, 50])
print("Original array:\n", my_array)
# Shuffle the array in-place
np.random.shuffle(my_array)
print("\nShuffled array:\n", my_array)

Output:

python arrayshuffle-图3
(图片来源网络,侵删)
Original array:
 [10 20 30 40 50]
Shuffled array:
 [50 10 40 20 30]

Option B: numpy.random.permutation() (Returns a new array)

This is often more useful because it returns a new, shuffled array and leaves the original untouched.

import numpy as np
original_array = np.array([100, 200, 300, 400, 500])
print("Original array:\n", original_array)
# Get a new shuffled array
shuffled_array = np.random.permutation(original_array)
print("\nNew shuffled array:\n", shuffled_array)
print("\nOriginal array is unchanged:\n", original_array)

Output:

Original array:
 [100 200 300 400 500]
New shuffled array:
 [400 100 500 200 300]
Original array is unchanged:
 [100 200 300 400 500]

Shuffling a Multi-dimensional NumPy Array

If you have a 2D array (like a matrix), np.random.shuffle() will shuffle the rows, not the individual elements.

import numpy as np
# A 2D array (3 rows, 4 columns)
matrix = np.array([
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
])
print("Original matrix:\n", matrix)
# Shuffles the rows
np.random.shuffle(matrix)
print("\nShuffled matrix (rows are shuffled):\n", matrix)

Output:

Original matrix:
 [[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
Shuffled matrix (rows are shuffled):
 [[ 5  6  7  8]
 [ 1  2  3  4]
 [ 9 10 11 12]]

Shuffling a Multi-dimensional Structure (e.g., a Deck of Cards)

Sometimes you don't want to shuffle the rows of a 2D array, but the individual "items" within it. For example, a deck of cards represented as a list of lists.

The best approach here is to flatten the structure, shuffle it, and then reshape it back to its original form.

Example: Shuffling a Deck of Cards

import random
# A deck of cards is a list of [rank, suit] pairs
deck = [
    ['2', 'Hearts'], ['3', 'Hearts'], ['4', 'Hearts'], ['5', 'Hearts'],
    ['2', 'Diamonds'], ['3', 'Diamonds'], ['4', 'Diamonds'], ['5', 'Diamonds'],
    # ... imagine the full deck
]
print("Original deck (first 5 cards):", deck[:5])
# 1. Flatten the list of lists into a single list of cards
flat_deck = [card for sublist in deck for card in sublist]
# A more readable way to flatten:
# flat_deck = []
# for sublist in deck:
#     for card in sublist:
#         flat_deck.append(card)
# 2. Shuffle the flattened list
random.shuffle(flat_deck)
# 3. Reshape the shuffled list back into the original structure
# This requires knowing the original shape
shuffled_deck = []
for i in range(0, len(flat_deck), len(deck[0])):
    shuffled_deck.append(flat_deck[i:i + len(deck[0])])
print("\nShuffled deck (first 5 cards):", shuffled_deck[:5])

Output:

Original deck (first 5 cards): [['2', 'Hearts'], ['3', 'Hearts'], ['4', 'Hearts'], ['5', 'Hearts'], ['2', 'Diamonds']]
Shuffled deck (first 5 cards): [['4', 'Diamonds'], ['2', 'Hearts'], ['5', 'Diamonds'], ['3', 'Hearts'], ['4', 'Hearts']]

Summary: Which one should I use?

Goal Best Method Key Characteristic
Shuffle a standard Python list random.shuffle(my_list) Modifies the list in-place.
Get a new shuffled list (keep original) random.shuffle(my_list.copy()) Creates a copy first, then shuffles the copy.
Shuffle a NumPy array (in-place) np.random.shuffle(my_array) Shuffles along the first axis (rows for 2D).
Get a new shuffled NumPy array shuffled = np.random.permutation(my_array) Returns a new array, original is untouched.
Shuffle items in a 2D structure Flatten -> Shuffle -> Reshape The most flexible and common pattern for this task.
分享:
扫描分享到社交APP
上一篇
下一篇