python random模块随机取list中的某个值


import random 
from random import randint

'''
random.randint()随机生一个整数int类型,可以指定这个整数的范围,同样有上限和下限值,python random.randint。
random.choice()可以从任何序列,比如list列表中,选取一个随机的元素返回,可以用于字符串、列表、元组等。
random.sample()可以从指定的序列中,随机的截取指定长度的片断,不作原地修改。
'''

list_one=["name","age",18]
choice_num=random.choice(list_one)
print(choice_num)

index_num=randint(1,1000)%len(list_one)
print(list_one[index_num])
print(random.sample(list_one,1)[0])

'''
利用下表随机取值
'''
def getsomeone(listobject):
    if isinstance(listobject, list) :
        index_num=randint(1,1000)%len(listobject)
        return listobject[index_num]
    else:
        return None
    '''
    利用random中的choice函数随机取值
    '''
def getsomeone1(listobject):
    if isinstance(listobject, list):
        someone=random.choice(listobject)
        return someone
    else:
        return None
    '''
    random.sample()可以从指定的序列中,随机的截取指定长度的片断,不作原地修改。
    '''
def getsomeone2(listobject):
    if isinstance(listobject, list):
        someone=random.sample(listobject,1)[0]
        return someone
    else:
        return None
    
    
print(getsomeone(list_one))
print(getsomeone1(list_one))
print(getsomeone2(list_one))
  

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM