ZhangZhihui's Blog  

To select a random item from the list or shuffle the list, you can use the choice and shuffle functions from the random module of the standard library.

The random.choice() function returns a randomly selected element from the list.

>>> import random

>>> colors = ['red', 'blue', 'green', 'yellow']

>>> random.choice(colors)

'blue'

>>> random.choice(colors)

'green'

The random.shuffle() function reorders the elements in the list.

>>> cities = ['Etah', 'Kasganj', 'Dhampur', 'Najibabad', 'Bareilly', 'Chennai', 'Bangalore']

>>> random.shuffle(cities)

>>> cities

['Bangalore', 'Kasganj', 'Najibabad', 'Chennai', 'Bareilly', 'Etah', 'Dhampur']

>>> random.shuffle(cities)

>>> cities

['Bareilly', 'Najibabad', 'Chennai', 'Kasganj', 'Dhampur', 'Bangalore', 'Etah']

This function modifies the list in-place; it does not return a new list.

posted on 2024-07-29 20:05  ZhangZhihuiAAA  阅读(28)  评论(0)    收藏  举报