Moduļa random metode choice

Moduļa random metode choice atgriež nejaušu elementu no sekvences (virknes, saraksta, korteža). Metodes parametrā norādām mums vajadzīgo sekvenci.

Sintakse

pythonimport random

random.choice(sekvence)

Piemērs

Iegūsim jebkuru no virknes elementiem:

pythontxt = 'abcde'
print(random.choice(txt))

Koda izpildes rezultāts:

python'e'

Piemērs

Tagad iegūsim nejaušu elementu sarakstā:

pythonlst = [1, 2, 3, 4, 5]
print(random.choice(lst))

Koda izpildes rezultāts:

python5

Piemērs

Izvadīsim jebkuru no korteža elementiem:

pythontpl = ('1', '2', '3', '4', '5')
print(random.choice(tpl))

Koda izpildes rezultāts:

python'4'

Skatiet arī

  • moduļa random metode shuffle,
    kas saķemmē sekvenci
  • moduļa random metode random,
    kas atgriež pseidonejaušu skaitli
  • moduļa random metode sample,
    kas atgriež nejaušu elementu izlasi no sekvences