30秒学会 Python 片段 · 2017年9月8日

30秒学会 Python 片段 – sample

Returns a random element from a list.

Use random.randint() to generate a random number that corresponds to an index in the list, return the element at that index.

random.sample() provides similar functionality to this snippet.

代码实现

from random import randint

def sample(lst):
  return lst[randint(0, len(lst) - 1)]

使用样例

sample([3, 7, 9, 11]) # 9