用用python輸出亂序後的列表
1. random.shuffle()函數
用python自帶的庫函數random.shuffle(list)可以輸出一個亂序的列表。
list =[1,2,3,4,5,6]
random.shuffle(list)
print(list)
2.自己定義程序
一種思路是使用產生一定範圍的隨機數,且不重複。然後亂序賦值給一個新的列表輸出即可。
import random
alist=input("請輸入一列數,以空格分隔:").split(" ") #將input進來用空格分開的數據保存在alist[]列表中
list=[] #初始化一個空列表,用來保存亂序後的數據
s=random.sample(range(len(alist)),len(alist)) #random.sample(範圍,n),此函數在範圍中隨機產生不重複的n個數。以列表形式返回n個數
#len(alist)輸入的數字個數
for i in range(0,len(alist)):
list.append(alist[s[i]]) #循環數字個數次,往list列表中順序append添加alist的第隨機位的數字
print("亂序結果:",end=" ") #end=" "用於避免換行,與下一個print用空格隔開
for x in list: #由於list輸出格式爲['',''],所以循環輸出每個數
print(x,end=' ')
使用了函數random.sample()產生一定範圍和個數的不相等的隨機數,並以列表形式返回。