Using a Loop to Pair Indexes in Python - 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()

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.

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')]

Related

How to make random number values for a dictionary that stay the same

Title isn't great, sorry.
I am new to python and I am playing around with dictionaries to further my understanding of them.
To practice, I am making a football team of 11 players. Each player is a dictionary stored in a list.
So each player will have its own dictionary but all the keys will be the same throughout, it's just the values that will change.
I have made the players positions and now I want to add the age of the player. This is what I have:
footballers = []
for populating in range(11): #populating = to get footballers
new_player = {"position": 'goalkeeper',}
footballers.append(new_player)
for baller in footballers[1:5]:
baller["position"] = 'defender'
print (baller)
for player in footballers[5:8]:
player["position"] = "midfield"
for player in footballers[8:11]:
player["position"] = "forward"
import random
for baller in footballers:
baller["age"] = random.randint (17, 34)
print (baller)
This works and I get the desired result. However, the age changes every time I run the code.
How would I make it so that I run it once and the value of the key stays the same?
I know I could just type the ages out myself but if I wanted to populate a whole league, I'm not doing that.
I've tried other ways such as making the age:value in another list of dictionaries but I couldn't figure out how to put the 2 together.
Is there something I'm missing here?
Thanks
A seed allows to 'randomly' populate a list with the same values every call.
It's important to have the seed outside the loop.
import random # good practice is to have imports at the top
footballers = []
for populating in range(11):
new_player = {"position": 'goalkeeper',}
footballers.append(new_player)
for baller in footballers[1:5]:
baller["position"] = 'defender'
print (baller)
for player in footballers[5:8]:
player["position"] = "midfield"
for player in footballers[8:11]:
player["position"] = "forward"
random.seed(42)
# the correct position is anywhere before the loop to have the same ages every call
for baller in footballers:
## random.seed(42) # Wrong position - will result in each player have the same age
baller["age"] = random.randint (17, 34)
print (baller)
Notes:
When you run your code in jupyter random.seed() needs to be in the same cell as the random call
42 is just an example, you can use any positive integer

Generating a list to store input data

I am writing a program that keeps tab of the score of a card game and by the completion of the game generates a table with names of players, points and total profit/loss. I need some advice on how to execute one crucial aspect of scoring keeping for this project and hence I'll start by giving you the main lines of code of the project:
# takes player information//
player_number = int(input('number of players:'))
cards_per_player = int(input('cards per player:'))
# takes player data and generates dictionary
player_dict = {}
for x in range(1,player_number+1):
player_dict["player{0}".format(x)] = input('name of player:')
print (player_dict)
# takes the dictionary values and creates a list
players_keys = list(player_dict.values())
# function that takes an input for the 'hands' won for each round for each player in the game...maximum hands for each player are 3 and minimum are 0.
def round():
counter_for_round = []
for i in range(0,(len(players_keys))):
score_per_player = int((input(str(players_keys[i])+':')))
counter_for_round.append(score_per_player)`
The counter_for_round variable stores data on each player's count of hands for any particular round. For example, if the total number of players were three, the list would look like: [1,1,0] or [3,0,0] or [2,1,0] and etc etc. Now, what I want it is to generate variables with empty lists for each item within the list 'players_keys'. So, for example, if players_keys = [a,b,c], I want to generate three variables, a b and c, which are empty lists in order for me to store the total scores within them for each player.
How do I go about this? Also, I know that this method can be quite detrimental and hence I am curious as to whether you can think of a simpler way to execute this?
Since you dont know how many players there are, you shouldnt try to create "new variables" for each player, but use a dictionary instead like you already did with player_dict.
So your result would be score = {key: list() for key in players_keys}, which is a dictionary with every player name as a key and an empty list as a value.
Also i'm not sure why you even need player_dict since the new score variable would include all important information. So maybe merging input of player names and list creation would be better.
# takes player data and generates dictionary
player_dict = dict()
for x in range(0, player_number):
player_name = input('name of player:')
player_dict[player_name] = list()
# takes the dictionary values and creates a list
players_keys = list(player_dict.keys())

Comparing a list to a file and then counting every time that element appears in a list and putting it into a dictionary

I have a list of political parties:
x = ['Green', 'Republicans' 'Democrats', 'Independent']
and then I have a file that lists out which district was won by the political party, there are roughly sixty entries. I have some starter code but I don't quite know how to continue on.
def party_winners (political_party, filename):
winning_party = {}
with open (filename,'r') as f:
for line in f:
results=line.split(',')
Basically all I want is to compare x, to every single list in my file, and see if something matches so if in the file Republicans won 50 times my dictionary will say:
winning_party = {'Republicans':50, 'Democrats': 35, 'Independents': 0}
I knew I forgot something my file is a list of
[county, votes, political party, person who ran]
Assuming that results is a list of the winners, in the exact form that they apear in x, you could do something like this:
winning_party = {}
for region in results:
if not region in winning_party:
winning_party[region] = 0
winning_party[region] += 1
This:
Creates the empty dictionary winning_party
Loops through all elements in your array of regions:
Checkings if the item is already in the dictionary and adds it if isn't
Increments the count on the item by 1
Given a list of winners lst, you can use collections.Counter directly:
from collections import Counter
c = Counter(lst)
How you obtain lst depends on the structure of your csv file.

How to put elements from a file into a 3D List? Python

I am trying to figure out how to get elements from a file into a 3D list.
For example, if my people.txt file looked like:
3 4
SallyLee
MallieKim
KateBrown
JohnDoe
TreyGreen
SarahKind
But I ONLY want SallyLee etc in the 3D list without the top numbers.
So far I have coded:
def main():
list = []
peopleFile = open("people.txt")
peopleRead = peopleFile.readlines()
for lines in peopleRead:
list.append([lines])
peopleFile.close()
print(list)
main()
This then prints it WITH the numbers, and not in a 3D list.
An example of what I am trying to do is:
[[[SallyLee],[MallieKim],[KateBrown]],[[JohnDoe],[TreyGreen],[SarahKind]]]
where every third person is "grouped" together.
I am not expecting anyone to code anything for me!
I just hope that someone can lead me into the right direction.
Thank you
First of all, if all you're looking for is strings (not numbers) you can start your for loop off with a condition to pass any element that has numbers. You can do this with the try:/except:.
Next you can use the parameters of the range function to make a list of the indices in which you're interested in. If you want to group by threes, you can have range make a list of the multiples of three (0,3,6,9,...)
Here's my code:
file = open('text.txt','r')
i = 0
names = []
for line in file:
line.split() #This will split each line into a list
try: #This will try to convert the first element of that list into an integer
if int(line[0]): #If it fails it will go to the next line
continue
except:
if not line.strip(): #This will skip empty lines
continue
names.append(line.strip()) #First let's put all of the names into a list
names = [names[i:i+3] for i in range(0,len(names)-1,3)]
print names
Output:
[['SallyLee', 'MallieKim', 'KateBrown'], ['JohnDoe', 'TreyGreen', 'SarahKind']]

Separating lists in a list through iteration

First off, this is a homework assignment, but I've been working on it for a week now and haven't made much headway. My goal for this function is to take a list of lists (each list contains data about a football player) and separate the lists based off of the teams which the players belong to. I also want to add up each player's data so that I wind up with one list for each team with all the player's stats combined.
Here's the code I have so far. The problem I'm currently running into is that some teams are printed multiple times with different data each time. Otherwise it appears to be working correctly. Also, we have the limitation imposed on us that we are not allowed to use classes.
def TopRushingTeam2010(team_info_2010): #running into trouble calculating the rusher rating for each team, it also prints out the same team multiple times but with different stats. And just not getting the right numbers and order.
total_yards = 0
total_TD = 0
total_rush = 0
total_fum = 0
#works mostly, but is returning some teams twice, with different stats each time, which
#should not be happening. so... yeah maybe fix that?
for item in team_info_2010:
team = item[0]
total_yards = item[2]
total_TD = item[3]
total_rush = item[1]
total_fum = item[4]
new_team_info_2010.append([team, total_yards, total_TD, total_rush, total_fum])
for other_item in team_info_2010:
if other_item[0] == team:
new_team_info_2010.remove([team, total_yards, total_TD, total_rush, total_fum])
total_yards = total_yards + other_item[2]
total_TD = total_TD + other_item[3]
total_rush = total_rush + other_item[1]
total_fum = total_fum + other_item[4]
new_team_info_2010.append([team, total_yards, total_TD, total_rush, total_fum])
Any help or tips as to which direction I should head, or if I'm even headed in the right direction?
One possible problem is that you are removing from team_info_2010 while you are iterating through the list. Try deleting that line of code. I don't see a clear reason why you would want to delete from team_info_2010 and behavior is often undefined when you modify an object while iterating through it. More specifically, try deleting the following line of code:
team_info_2010.remove(item)

Categories