代码语言:javascript复制
import random
List = ['a','b','c','d']
First = raw_input("First :")
for Item in List:
if First == Item:
List.remove(First)
Second=random.sample(List,1)
for Second in Second:
List.remove(Second)
Third=random.sample(List,1)
for Third in Third:
List.remove(Third)
Fourth=random.sample(x,1)
for Fourth in Fourth:
List.remove(Fourth)
print First '|' Second '|' Third '|' Fourth
代码解析
定义列表List
First为人为输入的第一个项
系统判断如果First属于列表List,则将First的值从列表List中去除
之后从列表List(已经去除First)中随机取一个值为Second,并从列表List中去除Second的值
再从列表List(已经去除First,Second)中随机取一个值为Third,并从列表List中去除Third的值
最后从列表List(已经去除First,Second和Third)中取值为Fourth
最后按照要求输出
每一个从列表中去除值前面的for循环的作用是:由于直接通过random取出的值依旧是列表形式,所以需要用for循环的方式把random的取值从列表转换成字符串。
把上面的例子改成函数模式:
代码语言:javascript复制import random
numName=""
def rmKey(listName,numName):
for numName in numName:
listName.remove(numName)
return numName
def listRandom(listName):
keyName=""
keyName=random.sample(listName,1)
return keyName
First=""
Second=""
Third=""
Fourth=""
List = ['a','b','c','d']
First = raw_input("First :")
for Item in List:
if First == Item:
rmKey(List,First)
Second=listRandom(List)
Second=rmKey(List,Second)
Third=listRandom(List)
Third=rmKey(List,Third)
Fourth=listRandom(List)
Fourth=rmKey(List,Fourth)
print First '|' Second '|' Third '|' Fourth