Hướng dẫn shuffle list python



Hàm shuffle() trong Python sắp xếp các item trong list một cách ngẫu nhiên.

Nội dung chính

  • Trả về giá trị
  • Chương trình Python ví dụ
  • random.shuffle() shuffles a list in place
  • random.sample() returns a new shuffled list
  • How to shuffle a string and tuple
  • Initialize the random number generator with random.seed()


Cú pháp

Cú pháp của shuffle() trong Python:

import random
random.shuffle(lst)

Ghi chú: Hàm này không có thể truy cập trực tiếp, vì thế chúng ta cần import random module và sau đó chúng ta cần gọi hàm này bởi sử dụng đối tượng random.

Chi tiết về tham số:

  • lst: Đây có thể là một list hoặc tuple.


Ví dụ sau minh họa cách sử dụng của hàm shuffle() trong Python.

import random
list = [20, 5, 10, 15, 50];
random.shuffle(list)
print ("List sau khi bị xáo trộn là: ",  list)
random.shuffle(list)
print ("List sau khi bị xáo trộn là: ",  list)

Chạy chương trình Python trên sẽ cho kết quả:

List sau khi bị xáo trộn là:  [10, 15, 50, 20, 5]
List sau khi bị xáo trộn là:  [20, 5, 10, 50, 15]




Miêu tả

Phương thức shuffle() sắp xếp các item trong list một cách ngẫu nhiên.

Cú pháp

Cú pháp của shuffle() trong Python:

shuffle (lst )

Ghi chú: Hàm này không có thể truy cập trực tiếp, vì thế chúng ta cần import math module và sau đó chúng ta cần gọi hàm này bởi sử dụng đối tượng math.

Chi tiết về tham số:

  • lst -- Đây có thể là một list hoặc tuple.

Quảng cáo

Trả về giá trị

Phương thức này trả về một list sau khi đã bị xáo trộn.

Chương trình Python ví dụ

Ví dụ sau minh họa cách sử dụng của shuffle() trong Python.

 
import random

list = [20, 16, 10, 5];
random.shuffle(list)
print "List sau khi bi xao tron la : ",  list

random.shuffle(list)
print "List sau khi bi xao tron la : ",  list

Chạy chương trình Python trên sẽ cho kết quả:

List sau khi bi xao tron la :  [16, 5, 10, 20]
List sau khi bi xao tron la :  [16, 5, 20, 10]

number_trong_python.jsp



Bài viết liên quan

  • 160 bài học ngữ pháp tiếng Anh hay nhất

  • 155 bài học Java tiếng Việt hay nhất

  • 100 bài học Android tiếng Việt hay nhất

  • 247 bài học CSS tiếng Việt hay nhất

  • 197 thẻ HTML cơ bản

  • 297 bài học PHP

  • 101 bài học C++ hay nhất

  • 97 bài tập C++ có giải hay nhất

  • 208 bài học Javascript có giải hay nhất

18 Tháng Một, 2021 48 Views

Code and details:

Python shuffle list of numbers / range
Python shuffle list of numbers
Python shuffle list of strings
Python shuffle array with seed
Python shuffle list of lists

import random
nums = [x for x in range(20)]
random.shuffle(nums)
print(nums)

—————————————————————————————————————————————————————
Code store

Socials

Facebook:
Facebook:
Twitter:

If you really find this channel useful and enjoy the content, you’re welcome to support me and this channel with a small donation via PayPal and Bitcoin.

In Python, you can shuffle (= randomize) a list, string, and tuple with random.shuffle() and random.sample().

  • random — Generate pseudo-random numbers — Python 3.8.1 documentation

random.shuffle() shuffles a list in place, and random.sample() returns a new randomized list. random.sample() can also be used for a string and tuple.

  • random.shuffle() shuffles a list in place
  • random.sample() returns a new shuffled list
  • How to shuffle a string and tuple
  • Initialize the random number generator with random.seed()

If you want to sort in ascending or descending order or reverse instead of shuffling, see the following articles.

  • Sort a list, string, tuple in Python (sort, sorted)
  • Reverse a list, string, tuple in Python (reverse, reversed)

random.shuffle() shuffles a list in place

You can shuffle a list in place with random.shuffle().

import random

l = list(range(5))
print(l)
# [0, 1, 2, 3, 4]

random.shuffle(l)
print(l)
# [1, 0, 4, 3, 2]

random.sample() returns a new shuffled list

random.sample() returns a new shuffled list. The original list remains unchanged.

random.sample() returns random elements from a list. Pass the list to the first argument and the number of elements to return to the second argument. See the following article for details.

  • Random sampling from a list in Python (random.choice, sample, choices)

By setting the total number of elements in the list to the second argument, random.sample() returns a new list with all elements randomly shuffled. You can get the total number of elements in the list with len().

l = list(range(5))
print(l)
# [0, 1, 2, 3, 4]

lr = random.sample(l, len(l))
print(lr)
# [0, 3, 1, 4, 2]

print(l)
# [0, 1, 2, 3, 4]

How to shuffle a string and tuple

Strings and tuples are immutable, so random.shuffle() that modifies the original object raises an error TypeError.

s = 'abcde'

# random.shuffle(s)
# TypeError: 'str' object does not support item assignment

t = tuple(range(5))
print(t)
# (0, 1, 2, 3, 4)

# random.shuffle(t)
# TypeError: 'tuple' object does not support item assignment

To shuffle strings or tuples, use random.sample(), which creates a new object.

random.sample() returns a list even when a string or tuple is specified to the first argument, so it is necessary to convert it to a string or tuple.

For strings, a list of characters is returned. Use the join() method to concatenate to a single string again.

  • Concatenate strings in Python (+ operator, join, etc.)
sr = ''.join(random.sample(s, len(s)))
print(sr)
# bedca

Use tuple() for tuples, which creates a tuple from a list.

  • Convert list and tuple to each other in Python
tr = tuple(random.sample(t, len(l)))
print(tr)
# (0, 1, 2, 4, 3)

Initialize the random number generator with random.seed()

You can initialize a random number generator with random.seed().

After initializing with the same seed, it is shuffled in the same way.

l = list(range(5))
random.seed(0)
random.shuffle(l)
print(l)
# [2, 1, 0, 4, 3]

l = list(range(5))
random.seed(0)
random.shuffle(l)
print(l)
# [2, 1, 0, 4, 3]