简体   繁体   中英

Two different random.choices from a list (python)

Complete python noob here but I am slowly wrapping my head around it. I am making a 1v1 Halo 3 tournament style program that randomly matches players and picks the map, gametype etc...

The problem I am having is that I don't know how to randomly recall two different strings from a list.

playerList = ["Player 1", "Player 2", "Player 3", "Player 4"]

So say this was the list of players, how would I print:

Player 1 vs Player 3

I have tried a few different things to no avail. I do have a little bit of an understanding of the random library but I can't figure out exactly how to do this

ie print random.choice(playerList) + " vs " + random.choice(playerList) eventually will have the same players versing each other when you've run it enough times...

Cheers

What you are looking for is random.sample . You want to pick 2 out of the list:

import random

playerList = ["Player 1", "Player 2", "Player 3", "Player 4"]
player1, player2 = random.sample(playerList, 2)
print '{} vs. {}'.format(player1, player2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM