python随机取列表元素 您所在的位置:网站首页 python在列表中随机抽取一个元素的值 python随机取列表元素

python随机取列表元素

2024-07-13 02:32| 来源: 网络整理| 查看: 265

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))



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有