Cara menggunakan SHUFFLING pada Python

Cara menggunakan SHUFFLING pada Python
angka Python


deskripsi

Semua elemenmengocok () metode urutan memerintahkan secara acak.


tatabahasa

Berikut ini adalah metode sintaks acak ():

import random

random.shuffle (lst )

Catatan: acak () tidak langsung dapat diakses, Anda perlu mengimpor modul acak, dan kemudian memanggil metode dengan objek statis acak.


parameter

  • lst - bisa menjadi urutan atau tupel.

Kembali Nilai

Mengembalikan urutan acak diurutkan.


contoh

Berikut ini menunjukkan contoh menggunakan () metode shuffle:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import random

list = [20, 16, 10, 5];
random.shuffle(list)
print "随机排序列表 : ",  list

random.shuffle(list)
print "随机排序列表 : ",  list

Setelah menjalankan contoh di atas output:

随机排序列表 :  [16, 5, 10, 20]
随机排序列表 :  [16, 5, 20, 10]

Cara menggunakan SHUFFLING pada Python
angka Python

Table of Contents

  • Randomly organize list elements in a matter of seconds
  • random.shuffle()
  • random.sample()
  • How to Shuffle and Return a New List?
  • Where to Go From Here?
  • How do I shuffle a list in Python?
  • Which function is used to shuffle a list?
  • How do you shuffle multiple lists in Python?

Randomly organize list elements in a matter of seconds

Photo by Carl Heyerdahl on Unsplash

It can be quite common that you have to work with a list:

  • You may get a list of products from an API call
  • You may get a list of people from a database
  • You may get a list of items in an online store by reading from a CSV file
  • You may get a list of numbers from a range

The list goes on.

There can be cases when you may need to randomly shuffle these elements. and Python already got your back.

There can be many paths that you can take to randomly shuffle these lists, but in this article, we are going to see 2 of them.

Let’s jump right in.

random.shuffle()

This method can be one of the most popular ones that are used.

All you have to do is import the module random and then call it with a list inside it.

It will then change the ordering of the elements in the list and place them randomly there.

Let’s take a look at it:

random.sample()

This method is similar to the previous one with a difference: It does not modify the original list. It instead returns a new sampled list.

You can also specify the number of sampled elements that you want to get as a result:

If you want to get the entire list shuffled, you simply need to mention the entire length as the second argument of the sample method:

That’s pretty much it.

There can be other methods out there as well, but let’s keep things simple with these two methods that you can start using right away in your job right now.

Thank you for taking the time to read this article all the way to the end.

I hope this helps you in some way.

Call random.shuffle(list) to randomize the order of the elements in the list after importing the random module with import random. This shuffles the list in place. If you need to create a new list with shuffled elements and leave the original one unchanged, use slicing list[:] to copy the list and call the shuffle function on the copied list.

How to Shuffle a List in Python?

Problem: You’ve got a Python list and you want to randomly reorder all elements?

Solution: No problem, use the shuffle function in Python’s random library.

Example: Here’s some code to show you how to do this:

import random

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

random.shuffle(a)
print(a)
# [6, 8, 5, 7, 2, 3, 9, 1, 4, 0]

random.shuffle(a)
print(a)
# [8, 4, 9, 2, 6, 3, 5, 7, 0, 1]

random.shuffle(a)
print(a)
# [1, 0, 7, 2, 4, 9, 5, 8, 3, 6]

random.shuffle(a)
print(a)
# [4, 6, 0, 5, 1, 3, 9, 2, 7, 8]

As the elements are randomly reordered, the result will look different when you’ll execute the same code snippet. Like any random function, the behavior is non-deterministic. Please also note that the list itself is shuffled—there’s no new list created.

You can try it yourself in the following interactive Python shell:

How to Shuffle and Return a New List?

The default random.shuffle(a) method modifies an existing list a. It works in-place. So, what if you want to shuffle the original list but return a new list while leaving the original list elements unchanged?

No problem—use slicing to copy the list.

import random

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

b = a[:]
random.shuffle(b)
print(b)

Exercise: Take a guess—what’s the output of this code snippet? You can check your guess in our interactive code shell:

Related articles:

  • How to copy a list?
  • Slicing
  • Python Lists [Ultimate Guide]
  • The random module explained
  • How to Shuffle Two Arrays in Unison in Python?

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

How do I shuffle a list in Python?

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.

Which function is used to shuffle a list?

shuffle() function in Python. The shuffle() is an inbuilt method of the random module. It is used to shuffle a sequence (list).

How do you shuffle multiple lists in Python?

Method : Using zip() + shuffle() + * operator In this method, this task is performed in three steps. Firstly, the lists are zipped together using zip(). Next step is to perform shuffle using inbuilt shuffle() and last step is to unzip the lists to separate lists using * operator.