goodgirlatx347
goodgirlatx347

Reputation: 31

Using a Loop to Pair Indexes in Python

Please be patient. I'm new to Python and only 1 month in. In this proect, I import a file that simulates a list of names with associated scores. I'm having a hard time creating a loop that will print out the 1st index and its associated pair. My program needs to divide the player list in half, and generate pairs using a player from each half of the list. For example, if there are 10 players sorted by rating, player 1 plays player 6, 2 plays 7, etc.

Can someone give me a quick guide into the correct direction? My sample code is below, which once completed, I will need to make this into a program with working functions.

def main():

    myfile = open('CHESS.txt','r')

    players = []

    for line in myfile:
        line = line.rstrip('\n')
        players.append(line)
        players.sort()


    for i in players:
        m=len(players)/2
        print(players[0], players[0+m])


    myfile.close()

main()

Upvotes: 1

Views: 817

Answers (2)

Johannes Charra
Johannes Charra

Reputation: 29933

Classic use case for zip:

>>> players = ["Player{}".format(i) for i in range(20)]
>>> half = len(players)/2
>>> pairs = zip(players[:half], players[half:])
>>> pairs
[('Player0', 'Player10'), ('Player1', 'Player11'), ('Player2', 'Player12'), ('Player3', 'Player13'), ('Player4', 'Player14'), ('Player5', 'Player15'), ('Player6', 'Player16'), ('Player7', 'Player17'), ('Player8', 'Player18'), ('Player9', 'Player19')]

Upvotes: 1

mdml
mdml

Reputation: 22902

You're close. You just need to use an index i for each element in your list.

m=len(players)/2
for i in range(m):
    print(players[i], players[i+m])

Note that this requires you have an even number of players.

Upvotes: 1

Related Questions