Python | interesting shuffle method

Pythonrandom the "shuffle random sequence item" is a knowledge that we often encounter in learning, today we have to simply learn about it!

solution

In learning this method we need to know about how he composed.

First: Python as a programming language

The second: third-party libraries

Third: This function

First, we introduce this third-party libraries, random library using the Python standard library of random numbers, random number generation library may be randomly specified range. Here's a brief introduction about his usage. We look at a map to it.

After simple random learn how to use the library, let us look at the shuffle function. We will learn how to use random shuffle to shuffle data module. In addition, learn how to shuffle Python lists and strings. We must first introduce random library when you use this function, otherwise the code is not able to perform.

py complete system of small series finishing thon tutorials from the most basic to the frame and then to project combat learning materials are finishing, given to every junior partner, I had wanted to learn programming py thon, or a career change, or college students, as well as work want to upgrade their skills, are welcome to join the junior partner to learn to learn.

Additional deduction skirt: 835 017 344, the purpose of this group is to only use the AC fans CSDN

1, random.shuffle syntax

random.shuffle (x, random)

shuffle method has two parameters. A two random numbers are optional. Shuffle law, for disorderly sequence will be played in place. That is, it changes the position of items in the list. We call the list of elements of randomization.

2, Python using random.shuffle the list reshuffle

import random

number_list =  [7,14,21,28,35,42,49,56,63,70]

print ( "the original list:", number_list)

random.shuffle(number_list)   #shuffle方法

print ( "for the first time after the reshuffle list:", number_list)

random.shuffle(number_list)

print ( "listed after the second reshuffle:", number_list)

Original list: [7, 14, 21, 28, 35, 42, 49, 56, 63, 70]

The following list:: first shuffle [35, 28, 70, 14, 21, 63, 7, 49, 42, 56]

After a second shuffling listed: [21, 7, 70, 28, 56, 14, 63, 42, 35, 49]

This is the result of the reshuffle list, we can see from the results output, the position of each item has changed. Solve our free exercise to generate random data, master data in Python random generation technology.

2.1 random.shuffle () Shuffle list of strings

import  random

string_list = [ "Paint It Black", "Gimme Shelter", "sympathy for the devil", "satisfactory", "You can not always get what you want."]

print ( "original list of strings:", string_list)

random.shuffle(string_list)      #shuffle方法

print ( "first string list after the shuffle:", string_list)

random.shuffle(string_list)

print ( "string list after the second shuffle:", string_list)

Original list of strings: [ 'Paint It Black', 'Gimme Shelter', 'sympathy for the devil', 'satisfaction', 'You can not always get what you want']

The first string list after the shuffle: [ 'Gimme Shelter', 'You can not always get what you want', 'sympathy for the devil', 'Paint It Black', 'satisfied']

A list of strings after the second shuffle: [ 'satisfactory', 'Gimme Shelter', 'Paint It Black', 'You can not always get what you want', 'sympathy for the devil']

This and the above example is the same.

2.2 Python shuffling list to get the same results every time

How to use the list parameter disordered arrangement, so that each time lead to the same result when disordered arrangement?

Module random random.seed () method, may produce the same results every shuffle. Let's see how to use the seed method in combination with random play method.

import  random

numbers  = [10, 20, 30, 40, 50, 60]

print  ("Original list: ", numbers )

random.seed(4)

random.shuffle(numbers)

print("reshuffled  list ", numbers)

numbers  = [10, 20, 30, 40, 50, 60]

random.seed(4)

random.shuffle(numbers)

print("reshuffled  list ", numbers)

Original  list:  [10, 20, 30, 40, 50, 60]

reshuffled  list  [40, 60, 50, 10, 30, 20]

reshuffled  list  [40, 60, 50, 10, 30, 20]

Note: Using the same seed value when the method is called before every shuffle, shuffle after the execution of multiple operations, we will get the same list.

3, a string restructuring in Python

random.shuffle available for string. In other words, it can not accept a string parameter. If you try the following error will occur.

We get the wrong type: "str" ​​object does not support item assignment. How then shuffle character string. We can use various methods to achieve this. Let us discuss one by one.

Converts a string to the list of characters.

Drag random list of characters.

List converting disordered array of strings.

import random

string_one = "pynative"

print ("Original String: ",  string_one)

char_list = list(string_one) #  convert string inti list

random.shuffle(char_list) #shuffle  the list

string_one = ''.join(char_list)

print ("shuffled  String is: ", string_one)

Original String:  pynative

shuffled String is:  eytavpin

So that we can properly execute the code

4, Python random shuffle not-in-place

As we have discussed, random shuffle in place, not returning any content. Now let's look at how the unordered list arranged in an inappropriate position. To perform a shuffle is not in place, we need to use simple random modular approach. random.sample () method returns a new list, which contains the sample size passed to it. If the sample size of the list we pass the same size, it returns a new list, which is a version of the original unordered list. Let's use an example to do this.

import random

numbers = [5, 10, 15, 20, 25]

print ("Original list :  ",  numbers)

new_list = random.sample(numbers,  len(numbers))

print ("List after  not in-place shuffle  : ",  new_list)

Original list :  [5, 10, 15, 20, 25]

List after not in-place  shuffle  :  [25, 5, 10, 20, 15]

As you can see, we use the example of a method to perform a non-place shuffle.

We first define a new list to store the new order, a new way to reuse them in random order.

5, the same primary sequence listing shuffle two Python

Suppose you want to shuffle both lists, but want to keep the same shuffle order. For example, a list contains the student's name, another list containing results.

import random

empName = ['Jhon', 'Emma', 'Kelly',  'Jason']

empAchievement = [90, 85, 87, 100]

print("Print Lists Before  Shuffling")

print("List Employee Names:  ", empName)

print("List Employee Salary:  ", empAchievement)

mapIndexPosition = list(zip(empName,  empAchievement))

random.shuffle(mapIndexPosition)

empName, empAchievement =  zip(*mapIndexPosition)

print("\nPrint Lists after  Shuffling")

print("List Employee Names:  ", empName)

print("List Employee  Salary: ", empAchievement)

Print Lists Before Shuffling

List Employee Names:  ['Jhon', 'Emma', 'Kelly', 'Jason']

List Employee Achievement:  [90, 85, 87, 100]

Print Lists after Shuffling

List Employee Names:  ('Jason', 'Jhon', 'Kelly', 'Emma')

List Employee  Achievement:  (100, 90, 87, 85)

Thus it is possible to list two positions while the random transformation.

6, the restructuring of multidimensional arrays in Python

Suppose you have a multi-dimensional array, and you want to be disordered. In this example, I used the numpy module creates a two-dimensional array. In addition, the use of numpy.random.shuffle () method, we can order processing for multidimensional arrays.              

Now, let's see how disordered multidimensional arrays in Python.

import numpy

print("Before Shufflling  2-dimensional array in Python")

sampleArray = numpy.arange(100, 240,  10)

sampleArray =  sampleArray.reshape(7,2)

print (sampleArray)

print("After Shufflling  2-dimensional array in Python")

newArray =  numpy.random.shuffle(sampleArray)

print (sampleArray)

Before Shufflling 2-dimensional array  in Python

[[100 110]

[120 130]

[140 150]

[160 170]

[180 190]

[200 210]

[220 230]]

After Shufflling 2-dimensional array  in Python

[[100 110]

[140 150]

[160 170]

[180 190]

[120 130]

[200 210]

[220 230]]

So that we can be a disordered arrangement of multi-dimensional arrays.

7, shuffle the dictionary in Python

Not possible to modify the dictionary in python. However, we can rearrange the order of iteration dictionary keys. Extracting all the keys from the dictionary and add it to the list, the list and disordered disordered array using the new key to access the dictionary values.

import random

studentDict = {'Eric':80, 'Scott':75,  'Jessa':95, 'Mike':66}

print("Dictionary Before  Shuffling")

print(studentDict)

keys =  list(studentDict.keys())

random.shuffle(keys)

ShuffledStudentDict = dict()

for key in keys:

ShuffledStudentDict.update({key:studentDict[key]})

print("\nDictionary after  Shuffling")

print(ShuffledStudentDict)

Dictionary Before Shuffling

{'Eric': 80, 'Scott': 75, 'Jessa':  95, 'Mike': 66}

Dictionary after Shuffling

{'Mike': 66, 'Scott': 75,  'Eric': 80, 'Jessa': 95}

We all know that the dictionary keys and values ​​is one to one, we obtain the corresponding values ​​from the corresponding key. In the above random transformation we first obtain the key and key values ​​corresponding to the acquired data

Epilogue

On the face shuffle function of learning, we need to pay attention to the following points:

1, when using this function, we must remember that the introduction of appropriate library, in this function we often have random libraries and library numpy library, import library after we re-execute the appropriate code.

2, in the shuffle function is not able to accept a string of this type of data, we need to convert the string into another data type. If the direct input string gives an error.

Guess you like

Origin blog.csdn.net/zhoulei124/article/details/91430995