用Python从列表lst中取n个元素

用Python从列表lst中取n个元素

4 个月前

有时,我们要从列表中取n个元素,我们通常可以采用以下几种方法:

一、使用random.sample()随机取n个元素

方法:导入random函数,设置取的元素个数。

import random
lst=["张三","李四","王五","赵六","麻七","侯八"]
print(random.sample(lst,3))

二、用列表推导式随机取元素

import random
lst=["张三","李四","王五","赵六","麻七","侯八"]
print([random.choice(lst) for i in range(3)])

三、用iter()迭代函数实现按顺序取n个元素

lst=["张三","李四","王五","赵六","麻七","侯八"]