zoukankan      html  css  js  c++  java
  • 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))
      
    
  • 相关阅读:
    基本语句
    mysql多表查询方法(join)
    MySQL JOIN 多表连接
    MySQL SHOW INDEX语法的实际应用
    1.索引作用
    MySQL索引和优化查询
    mysql复合索引、普通索引总结
    mysql 索引相关
    for循环的break和continue
    保护程序猿滴眼睛---修改VS 2012 编辑器颜色
  • 原文地址:https://www.cnblogs.com/tallme/p/11173422.html
Copyright © 2011-2022 走看看