编写一个 Python 程序,对给定序列中的所有元素进行随机排序。


假设您有一个数据框,并且需要对其中一个序列的所有数据进行随机排序,

The original series is
0    1
1    2
2    3
3    4
4    5
dtype: int64
The shuffled series is :
0    2
1    1
2    3
3    5
4    4
dtype: int64

方案 1

  • 定义一个序列。

  • 应用随机排序方法,该方法将序列数据作为参数并对其进行排序。

data = pd.Series([1,2,3,4,5])
print(data)
rand.shuffle(data)

示例

让我们看看下面的代码来更好地理解 -

import pandas as pd
import random as rand
data = pd.Series([1,2,3,4,5])
print("original series is\n",data)
rand.shuffle(data)
print("shuffles series is\n",data)

输出

original series is
0    1
1    2
2    3
3    4
4    5
dtype: int64
shuffles series is
0    2
1    3
2    1
3    5
4    4
dtype: int64

方案 2

  • 定义一个序列。

  • 创建一个 for 循环来访问序列数据并在 j 变量中生成随机索引。定义如下,

for i in range(len(data)-1, 0, -1):
   j = random.randint(0, i + 1)
  • 将 data[i] 与随机索引位置处的元素交换,

data[i], data[j] = data[j], data[i]

示例

让我们看看下面的代码来更好地理解 -

import pandas as pd
import random
data = pd.Series([1,2,3,4,5])
print ("The original series is \n", data)
for i in range(len(data)-1, 0, -1):
   j = random.randint(0, i + 1)
   data[i], data[j] = data[j], data[i]
print ("The shuffled series is : \n ", data)

输出

The original series is
0    1
1    2
2    3
3    4
4    5
dtype: int64
The shuffled series is :
0    2
1    1
2    3
3    5
4    4
dtype: int64

更新于: 2021年2月24日

204 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告