简体   繁体   中英

How to assign a variable name from a list then delete it?

I want to create a function where it takes a list of names entered by the user. If there is an even number of players, it will randomly print out the names until there is no more names left. If there is an odd number, it will assign a variable name to the last name entered, then delete it from the list. Then it will do the same as the even number of players. I want to be able to use the last name later on in the program.

Here's what I have so far. It is giving me an error reading,

"raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width)"

def randName(teamNames):
    if len(teamNames) % 2 ==0:
        randomname = random.randrange(0, len(teamNames))
        return teamNames.pop(randomname)
    else:
        lastName = teamNames[-1]
        teamNames.pop()
from random import shuffle

def random_pairings(team_names):
    # randomize order
    team_names = list(team_names)
    shuffle(team_names)
    # remove 'odd man out'
    leftover = team_names.pop() if len(team_names) % 2 else None
    # get pairings
    trick = [iter(team_names)] * 2   # two pointers to *same* iterator
    pairs = list(zip(*trick))
    return pairs, leftover

which gives

>>> random_pairings("abcdefg")
([('g', 'c'), ('d', 'f'), ('b', 'e')], 'a')

so you can use it like

tennis_players = ["Dimitrov", "Herbert", "Sock", "Tomic", "Thiem"]

pairs, leftover = random_pairings(tennis_players)
for a,b in pairs:
    print("{} vs {}".format(a, b))
if leftover:
    print("{} sits this round out.".format(leftover))

giving

Tomic vs Herbert
Sock vs Dimitrov
Thiem sits this round out.

You just have to use randint :

def randName(teamNames):
    if len(teamNames) % 2 ==0:
        randomname = random.randint(0, len(teamNames))
        return teamNames.pop(randomname)
    else:
        lastName = teamNames[-1]
        teamNames.pop()

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