杰瑞科技汇

Python list shuffle如何随机打乱列表顺序?

Of course! Shuffling a list in Python is a common task, and the primary way to do it is by using the random module.

Python list shuffle如何随机打乱列表顺序?-图1
(图片来源网络,侵删)

Here's a complete guide covering the best methods, important distinctions, and examples.

The Main Method: random.shuffle()

This is the most direct and common way to shuffle a list in-place. This means it modifies the original list directly and does not return a new one.

How to Use It

  1. Import the random module.
  2. Call random.shuffle(your_list).

Example

import random
# 1. Create a list
my_list = ['apple', 'banana', 'cherry', 'date', 'elderberry']
print(f"Original list: {my_list}")
# 2. Shuffle the list in-place
random.shuffle(my_list)
# 3. The original list is now modified
print(f"Shuffled list: {my_list}

Output (will be different each time):

Original list: ['apple', 'banana', 'cherry', 'date', 'elderberry']
Shuffled list: ['date', 'elderberry', 'apple', 'banana', 'cherry']

Important: random.shuffle() vs. random.sample()

A common point of confusion is between shuffle() and sample(). It's crucial to understand the difference.

Python list shuffle如何随机打乱列表顺序?-图2
(图片来源网络,侵删)
Feature random.shuffle() random.sample()
Purpose Shuffles a list in-place. Creates a new list with a specified number of unique items.
Return Value None (it modifies the list directly). A new list containing the selected items.
Original List Is modified. Is not changed.
Common Use When you want to randomize the order of an existing list. When you want to pick a few random items from a list without changing it.

Example of random.sample()

import random
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Get 3 unique random elements from the list
# The original list remains unchanged
random_elements = random.sample(my_list, 3)
print(f"Original list: {my_list}")
print(f"Randomly sampled elements: {random_elements}")

Output:

Original list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Randomly sampled elements: [8, 2, 5]

How to Shuffle and Get a New List (Without Modifying the Original)

Sometimes you don't want to change your original list. The best way to do this is by creating a copy of the list and then shuffling the copy.

Method 1: Slicing (Most Pythonic)

This is the most common and readable way to create a copy.

import random
original_list = [1, 2, 3, 4, 5]
print(f"Original list: {original_list}")
# Create a copy using slicing [:] and shuffle the copy
shuffled_copy = original_list[:] # This is a shallow copy
random.shuffle(shuffled_copy)
print(f"Shuffled copy: {shuffled_copy}")
print(f"Original list (unchanged): {original_list}")

Output:

Python list shuffle如何随机打乱列表顺序?-图3
(图片来源网络,侵删)
Original list: [1, 2, 3, 4, 5]
Shuffled copy: [3, 1, 5, 2, 4]
Original list (unchanged): [1, 2, 3, 4, 5]

Method 2: The list() Constructor

You can also pass the original list to the list() constructor to make a copy.

import random
original_list = [1, 2, 3, 4, 5]
shuffled_copy = list(original_list) # Creates a new list
random.shuffle(shuffled_copy)
print(f"Shuffled copy: {shuffled_copy}")
print(f"Original list (unchanged): {original_list}")

Shuffling a List of Numbers (e.g., for a Deck of Cards)

If you need to generate a shuffled list of numbers, you can combine range() and sample().

import random
# Create a shuffled list of numbers from 0 to 51 (like a deck of cards)
shuffled_deck = random.sample(range(52), 52)
print(f"First 10 cards of the shuffled deck: {shuffled_deck[:10]}")

Output:

First 10 cards of the shuffled deck: [41, 18, 7, 29, 50, 12, 33, 4, 21, 0]

Summary: Which Method to Use?

Your Goal Recommended Method Why?
Shuffle an existing list permanently. random.shuffle(my_list) It's the direct, in-place method designed for this exact purpose.
Get a shuffled version but keep the original. shuffled_copy = my_list[:] then random.shuffle(shuffled_copy) This is clean, readable, and creates a new list to work with.
Pick a few random items from a list. random.sample(my_list, k=3) It's the right tool for the job, designed for sampling without replacement.
Generate a shuffled list of numbers. random.sample(range(n), n) Efficient and clear way to create a sequence of unique, shuffled numbers.
分享:
扫描分享到社交APP
上一篇
下一篇