1

I am trying to locate a random value from one array in another array:

team1Players = random.sample(activePlayers, 4)
print(team1Players[0])
index1 = overallPoints.index(f'{team1Players[0]}')

The above code yields the following output:

/Users/johnbeatty/PycharmProjects/THTTeamMakerv2/venv/bin/python /Users/johnbeatty/PycharmProjects/THTTeamMakerv2/main.py
playerName 
Traceback (most recent call last):
  File "/Users/johnbeatty/PycharmProjects/THTTeamMakerv2/main.py", line 237, in <module>
    index1 = overallPoints.index(f'{team1Players[0]}')
ValueError: 'playerName' is not in list

Process finished with exit code 1

I do not see why there should be a problem here; Python clearly recognizes the playerName and its name in the list... Would anybody be able to help me out here?

  • Your code is incomplete. What does `overallPoints` contain? Are you sure it's a list of player names? Maybe print out the list to make sure it's containing the data you expect, or use a debugger. – Miguel Guthridge Feb 26 '22 at 03:01

2 Answers2

3

The issue in this line: overallPoints.index(f'{team1Players[0]}' is that you are trying to search for a player name in overallPoints, which is a list of tuples. You won't find any player names by themselves there. You will only find tuples.

Try this instead:

import random 

activePlayers = ["Jack", "Ken", "Kyle", "Donald", "Amy"]
overallPoints = [("Jack", 10), ("Ken", 15), ("Kyle", 20), ("Donald", 30), 
("Amy", 40)]

team1Players = random.sample(activePlayers, 4)
index1 = [i[0] for i in overallPoints].index(team1Players[0])
print(team1Players)

Some additional notes:

  • If you are concerned about the speed or complexity of the proposed approach, look through this related stackoverflow post for other suggestions on how to use the .index() function when parsing a list of tuples.
  • I used the fake data above when testing my approach since activePlayers and overallPoints was not provided.
  • I assumed that a player from activePlayers would always be present in one of the tuples in overallPoints.
  • I assumed that player names are unique. If this is not true and the sampled player from activePlayer has the same name as another player that exists in activePlayer, then the program as is will only return the index of the first appearance of the player in overallPoints.
0

It's because overallPoints array does not have a value 'playerName'.

You should add the value inside overallPoints.

Flair
  • 2,609
  • 1
  • 29
  • 41
Haneen Mahdin
  • 1,000
  • 1
  • 7
  • 13
  • I forgot to specify— overallPoints is a list of tuples, [(playerName, x), (player2Name, y), ... (player16Name, z)]. Is there a way to index the first tuple value? Thanks for your response! – johnbeatty02 Feb 26 '22 at 03:25