I have a Python dictionary that looks like this:
{'Aitkin': ['Carlton', 'Cass', 'Crow Wing', 'Itasca',
'Kanabec', 'Mille Lacs', 'Pine', 'St. Louis'], 'Anoka':
['Chisago', 'Hennepin', 'Isanti', 'Ramsey', 'Sherburne',
'Washington'], 'Becker': ['Clay', 'Clearwater', 'Hubbard',
'Mahnomen', 'Norman', 'Otter Tail', 'Wadena'], 'Beltrami':
['Cass', 'Clearwater', 'Hubbard', 'Itasca', 'Koochiching',
'Lake of the Woods', 'Marshall', 'Pennington', 'Roseau'],
'Benton': ['Mille Lacs', 'Morrison', 'Sherburne', 'Stearns'], 'Big
Stone': ['Lac qui Parle', 'Stevens', 'Swift', 'Traverse'], 'Blue
Earth': ['Brown', 'Faribault', 'Le Sueur', 'Martin',
'Nicollet', 'Waseca', 'Watonwan'], 'Brown': ['Blue Earth',
'Cottonwood', 'Nicollet', 'Redwood', 'Renville', 'Watonwan'],
'Carlton': ['Aitkin', 'Pine', 'St. Louis'], 'Carver': ['Hennepin',
'McLeod', 'Scott', 'Sibley', 'Wright'], 'Cass': ['Aitkin',
'Beltrami', 'Crow Wing', 'Hubbard', 'Itasca', 'Morrison',
'Todd', 'Wadena'], 'Chippewa': ['Kandiyohi', 'Lac qui Parle',
'Renville', 'Swift', 'Yellow Medicine'], 'Chisago': ['Anoka',
'Isanti', 'Kanabec', 'Pine', 'Washington'], 'Clay': ['Becker',
'Norman', 'Otter Tail', 'Wilkin'], 'Clearwater': ['Becker',
'Beltrami', 'Hubbard', 'Mahnomen', 'Pennington', 'Polk'],
'Cook': ['Lake'], 'Cottonwood': ['Brown', 'Jackson', 'Murray',
'Nobles', 'Redwood', 'Watonwan'], 'Crow Wing': ['Aitkin', 'Cass',
'Mille Lacs', 'Morrison'], 'Dakota': ['Goodhue', 'Hennepin',
'Ramsey', 'Rice', 'Scott', 'Washington'], 'Dodge': ['Goodhue',
'Mower', 'Olmsted', 'Rice', 'Steele'], 'Douglas': ['Grant', 'Otter
Tail', 'Pope', 'Stearns', 'Stevens', 'Todd'], 'Faribault': ['Blue
Earth', 'Freeborn', 'Martin', 'Waseca'], 'Fillmore': ['Houston',
'Mower', 'Olmsted', 'Winona'], 'Freeborn': ['Faribault', 'Mower',
'Steele', 'Waseca'], 'Goodhue': ['Dakota', 'Dodge', 'Olmsted',
'Rice', 'Wabasha'], 'Grant': ['Douglas', 'Otter Tail', 'Pope',
'Stevens', 'Traverse', 'Wilkin'], 'Hennepin': ['Anoka', 'Carver',
'Dakota', 'Ramsey', 'Scott', 'Sherburne', 'Wright'],
'Houston': ['Fillmore', 'Winona'], 'Hubbard': ['Becker', 'Beltrami',
'Cass', 'Clearwater', 'Wadena'], 'Isanti': ['Anoka', 'Chisago',
'Kanabec', 'Mille Lacs', 'Pine', 'Sherburne'], 'Itasca': ['Aitkin',
'Beltrami', 'Cass', 'Koochiching', 'St. Louis'], 'Jackson':
['Cottonwood', 'Martin', 'Nobles', 'Watonwan'], 'Kanabec': ['Aitkin',
'Chisago', 'Isanti', 'Mille Lacs', 'Pine'], 'Kandiyohi': ['Chippewa',
'Meeker', 'Pope', 'Renville', 'Stearns', 'Swift'], 'Kittson':
['Marshall', 'Roseau'], 'Koochiching': ['Beltrami', 'Itasca', 'Lake
of the Woods', 'St. Louis'], 'Lac qui Parle': ['Big Stone',
'Chippewa', 'Swift', 'Yellow Medicine'], 'Lake': ['Cook', 'St.
Louis'], 'Lake of the Woods': ['Beltrami', 'Koochiching', 'Roseau'],
'Le Sueur': ['Blue Earth', 'Nicollet', 'Rice', 'Scott', 'Sibley',
'Waseca'], 'Lincoln': ['Lyon', 'Pipestone', 'Yellow Medicine'],
'Lyon': ['Lincoln', 'Murray', 'Pipestone', 'Redwood', 'Yellow
Medicine'], 'Mahnomen': ['Becker', 'Clearwater', 'Norman', 'Polk'],
'Marshall': ['Beltrami', 'Kittson', 'Pennington', 'Polk', 'Roseau'],
'Martin': ['Blue Earth', 'Faribault', 'Jackson', 'Watonwan'],
'McLeod': ['Carver', 'Meeker', 'Renville', 'Sibley', 'Wright'],
'Meeker': ['Kandiyohi', 'McLeod', 'Renville', 'Stearns', 'Wright'],
'Mille Lacs': ['Aitkin', 'Benton', 'Crow Wing', 'Isanti',
'Kanabec', 'Morrison', 'Sherburne'], 'Morrison': ['Benton',
'Cass', 'Crow Wing', 'Mille Lacs', 'Stearns', 'Todd'], 'Mower':
['Dodge', 'Fillmore', 'Freeborn', 'Olmsted', 'Steele'], 'Murray':
['Cottonwood', 'Lyon', 'Nobles', 'Pipestone', 'Redwood', 'Rock'],
'Nicollet': ['Blue Earth', 'Brown', 'Le Sueur', 'Renville', 'Sibley'],
'Nobles': ['Cottonwood', 'Jackson', 'Murray', 'Rock'], 'Norman':
['Becker', 'Clay', 'Mahnomen', 'Polk'], 'Olmsted': ['Dodge',
'Fillmore', 'Goodhue', 'Mower', 'Wabasha', 'Winona'], 'Otter Tail':
['Becker', 'Clay', 'Douglas', 'Grant', 'Wadena', 'Wilkin'],
'Pennington': ['Beltrami', 'Clearwater', 'Marshall', 'Polk', 'Red
Lake'], 'Pine': ['Aitkin', 'Carlton', 'Chisago', 'Isanti',
'Kanabec'], 'Pipestone': ['Lincoln', 'Lyon', 'Murray', 'Rock'],
'Polk': ['Clearwater', 'Mahnomen', 'Marshall', 'Norman',
'Pennington', 'Red Lake'], 'Pope': ['Douglas', 'Grant',
'Kandiyohi', 'Stearns', 'Stevens', 'Swift'], 'Ramsey': ['Anoka',
'Dakota', 'Hennepin', 'Washington'], 'Red Lake': ['Pennington',
'Polk'], 'Redwood': ['Brown', 'Cottonwood', 'Lyon', 'Murray',
'Renville', 'Yellow Medicine'], 'Renville': ['Brown', 'Chippewa',
'Kandiyohi', 'McLeod', 'Meeker', 'Nicollet', 'Redwood',
'Sibley', 'Yellow Medicine'], 'Rice': ['Dakota', 'Dodge',
'Goodhue', 'Le Sueur', 'Scott', 'Steele', 'Waseca'], 'Rock':
['Murray', 'Nobles', 'Pipestone'], 'Roseau': ['Beltrami', 'Kittson',
'Lake of the Woods', 'Marshall'], 'Scott': ['Carver', 'Dakota',
'Hennepin', 'Le Sueur', 'Rice', 'Sibley'], 'Sherburne': ['Anoka',
'Benton', 'Hennepin', 'Isanti', 'Mille Lacs', 'Stearns',
'Wright'], 'Sibley': ['Carver', 'Le Sueur', 'McLeod', 'Nicollet',
'Renville', 'Scott'], 'St. Louis': ['Aitkin', 'Carlton', 'Itasca',
'Koochiching', 'Lake'], 'Stearns': ['Benton', 'Douglas',
'Kandiyohi', 'Meeker', 'Morrison', 'Pope', 'Sherburne',
'Todd', 'Wright'], 'Steele': ['Dodge', 'Freeborn', 'Mower', 'Rice',
'Waseca'], 'Stevens': ['Big Stone', 'Douglas', 'Grant', 'Pope',
'Swift', 'Traverse'], 'Swift': ['Big Stone', 'Chippewa',
'Kandiyohi', 'Lac qui Parle', 'Pope', 'Stevens'], 'Todd':
['Cass', 'Douglas', 'Morrison', 'Otter Tail', 'Stearns', 'Wadena'],
'Traverse': ['Big Stone', 'Grant', 'Stevens', 'Wilkin'], 'Wabasha':
['Goodhue', 'Olmsted', 'Winona'], 'Wadena': ['Becker', 'Cass',
'Hubbard', 'Otter Tail', 'Todd'], 'Waseca': ['Blue Earth',
'Faribault', 'Freeborn', 'Le Sueur', 'Rice', 'Steele'],
'Washington': ['Anoka', 'Chisago', 'Dakota', 'Ramsey'], 'Watonwan':
['Blue Earth', 'Brown', 'Cottonwood', 'Jackson', 'Martin'], 'Wilkin':
['Clay', 'Grant', 'Otter Tail', 'Traverse'], 'Winona': ['Fillmore',
'Houston', 'Olmsted', 'Wabasha'], 'Wright': ['Carver', 'Hennepin',
'McLeod', 'Meeker', 'Sherburne', 'Stearns'], 'Yellow Medicine':
['Chippewa', 'Lac qui Parle', 'Lincoln', 'Lyon', 'Redwood',
'Renville']}
The keys in the dictionary represent the nodes, while the values(lists) represent nodes of neighbors of the key. This is an undirected unweighted graph.
Is there some function to implement this in networkx or some network analysis or graph-related libraries?
You can use the nx.Graph constructor -- it will add additional nodes if they don't appear as keys in the original dictionary (data represents the dictionary in the original question):
import networkx as nx
graph = nx.Graph(data)
Related
I have this list of dictionaries:
artist_and_tags = [{u'Yo La Tengo': ['indie', 'indie rock', 'seen live', 'alternative', 'indie pop', 'rock', 'post-rock', 'dream pop', 'shoegaze', 'noise pop', 'folk', 'experimental', 'alternative rock', 'american', 'lo-fi', 'pop', 'new jersey', 'yo la tengo', 'usa', 'noise rock', '90s', 'noise', '00s', 'ambient', 'post-punk', '80s', 'mellow', 'psychedelic', 'hoboken', 'experimental rock', 'singer-songwriter', 'post rock', 'electronic', 'female vocalists', 'alt-country', 'dreamy', 'matador', 'chillout', 'instrumental', 'favorites', 'punk', 'electronica', 'slowcore', 'folk rock', 'new wave', 'jazz', 'eclectic', 'new york', 'emo']}, {u'Radiohead': ['alternative', 'alternative rock', 'rock', 'indie', 'electronic', 'seen live', 'british', 'britpop', 'indie rock', 'experimental', 'radiohead', 'progressive rock', '90s', 'electronica', 'art rock', 'experimental rock', 'post-rock', 'psychedelic', 'uk', 'male vocalists', 'pop', '00s', 'ambient', 'chillout', 'progressive', 'favorites', 'melancholic', 'awesome', 'overrated', 'english', 'beautiful', 'classic rock', 'genius', 'melancholy', 'better than radiohead', 'trip-hop', 'idm', 'indie pop', 'emo']}, {u'Portishead': ['trip-hop', 'electronic', 'female vocalists', 'chillout', 'trip hop', 'alternative', 'electronica', 'seen live', 'downtempo', 'british', 'indie', 'portishead', 'experimental', 'ambient', 'female vocalist', 'alternative rock', '90s', 'lounge', 'mellow', 'bristol', 'jazz', 'psychedelic', 'chill', 'melancholic', 'triphop', 'uk', 'rock', 'bristol sound', 'acid jazz', 'lo-fi']}]
which I'm using to get relatedness between artists.
for that, I'm doing:
tags0 = set(artist_and_tags[0].values()[0])
tags1 = set(artist_and_tags[1].values()[0])
tags2 = set(artist_and_tags[2].values()[0])
then:
intersection1 = tags0 & tags1
intersection2 = tags0 & tags2
intersection3 = tags1 & tags2
so:
print (intersection1, len(intersection1), intersection2, len(intersection), intersection3, len(intersection3))
shows me that "Yo La Tengo" is closer to "Radiohead" than "Portishead", with 20 intersected tags.
this code seems a bit redundant, however...
QUESTION:
Is there a way to use this logic in a for loop (or wrapped in a simple function), so it works with a dictionary with n artists(keys)?
You can use itertools.combinations.
import itertools
import collections
ArtistTags = collections.namedtuple('ArtistTags', ('name', 'tags'))
tags = (ArtistTags(artist, set(tags))
for artists_dict in artist_and_tags
for artist, tags in artists_dict.items())
artist_pairings = itertools.combinations(tags, 2)
intersections = ((len(a.tags & b.tags), a, b) for a, b in artist_pairings)
for n, a, b in sorted(intersections, reverse=True):
print(n, a.name, b.name)
output:
20 Yo La Tengo Radiohead
16 Yo La Tengo Portishead
16 Radiohead Portishead
I got this question Automate the boring Stuff book. The Code is also given there but When I was Practising this on my own the problem I am getting is this code is not writing in the files after the first for loop.
import random
import os
capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix',
'Arkansas': 'Little Rock', 'California': 'Sacramento', 'Colorado': 'Denver',
'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee',
'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', 'Idaho': 'Boise', 'Illinois':
'Springfield', 'Indiana': 'Indianapolis', 'Iowa': 'Des Moines', 'Kansas':
'Topeka', 'Kentucky': 'Frankfort', 'Louisiana': 'Baton Rouge', 'Maine':
'Augusta', 'Maryland': 'Annapolis', 'Massachusetts': 'Boston', 'Michigan':
'Lansing', 'Minnesota': 'Saint Paul', 'Mississippi': 'Jackson', 'Missouri':
'Jefferson City', 'Montana': 'Helena', 'Nebraska': 'Lincoln', 'Nevada':
'Carson City', 'New Hampshire': 'Concord', 'New Jersey': 'Trenton',
'New Mexico': 'Santa Fe', 'New York': 'Albany', 'North Carolina': 'Raleigh',
'North Dakota': 'Bismarck', 'Ohio': 'Columbus', 'Oklahoma': 'Oklahoma City',
'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', 'Rhode Island': 'Providence',
'South Carolina': 'Columbia', 'South Dakota': 'Pierre', 'Tennessee':
'Nashville', 'Texas': 'Austin', 'Utah': 'Salt Lake City', 'Vermont':
'Montpelier', 'Virginia': 'Richmond', 'Washington': 'Olympia',
'West Virginia': 'Charleston', 'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'}
#print (capitals)
for q in range(35):
quizfile = open("capitalquiz%s.txt" %(q + 1), 'w')
answerfile = open("Answerfile%s.txt"%(q + 1),'w')
quizfile.write('Name:\n\nDate:\n\nPeriod:\n\n')
quizfile.write((' ' * 20) + 'State Capitals Quiz (Form %s)' % (q + 1))
quizfile.write('\n\n')
states = list(capitals.keys())
random.shuffle(states)
quizfile.write("wefkjqennqkeanfeqkjn")
for i in range(50):
correct_answer = capitals[states[i]]
wrong_answer = list(capitals.values())
del wrong_answer[correct_answer.index(correct_answer)]
wrong_answers = random.sample(wrong_answer,3)
answer_option = wrong_answers + [correct_answer]
random.shuffle(answer_option)
for item in range(50):
#quizfile.write("******************************************************")
quizfile.write("%s.what is the capital of %s" %(item+1,states[item]))
for i in range(4):
quizfile.write("%s. %s\n" %('ABCD'[i],answer_option[i]))
answerfile.write("%s. %s\n" %(q+1,'ABCD'[answer_option.index(correct_answer)]))
quizfile.close()
answerfile.close()
You've got some for loops that need to be nested within others. You're attempting to access out of scope variables as it is now.
Your code, cleaned up:
import random
import os
capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix',
'Arkansas': 'Little Rock', 'California': 'Sacramento', 'Colorado': 'Denver',
'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee',
'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', 'Idaho': 'Boise', 'Illinois':
'Springfield', 'Indiana': 'Indianapolis', 'Iowa': 'Des Moines', 'Kansas':
'Topeka', 'Kentucky': 'Frankfort', 'Louisiana': 'Baton Rouge', 'Maine':
'Augusta', 'Maryland': 'Annapolis', 'Massachusetts': 'Boston', 'Michigan':
'Lansing', 'Minnesota': 'Saint Paul', 'Mississippi': 'Jackson', 'Missouri':
'Jefferson City', 'Montana': 'Helena', 'Nebraska': 'Lincoln', 'Nevada':
'Carson City', 'New Hampshire': 'Concord', 'New Jersey': 'Trenton',
'New Mexico': 'Santa Fe', 'New York': 'Albany', 'North Carolina': 'Raleigh',
'North Dakota': 'Bismarck', 'Ohio': 'Columbus', 'Oklahoma': 'Oklahoma City',
'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', 'Rhode Island': 'Providence',
'South Carolina': 'Columbia', 'South Dakota': 'Pierre', 'Tennessee':
'Nashville', 'Texas': 'Austin', 'Utah': 'Salt Lake City', 'Vermont':
'Montpelier', 'Virginia': 'Richmond', 'Washington': 'Olympia',
'West Virginia': 'Charleston', 'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'}
for q in range(35):
quizfile = open("capitalquiz%s.txt" %(q + 1), 'w')
answerfile = open("Answerfile%s.txt"%(q + 1),'w')
quizfile.write('Name:\n\nDate:\n\nPeriod:\n\n')
quizfile.write((' ' * 20) + 'State Capitals Quiz (Form %s)' % (q + 1))
quizfile.write('\n\n')
states = list(capitals.keys())
random.shuffle(states)
for i in range(50):
correct_answer = capitals[states[i]]
wrong_answer = list(capitals.values())
del wrong_answer[correct_answer.index(correct_answer)]
wrong_answers = random.sample(wrong_answer,3)
answer_option = wrong_answers + [correct_answer]
random.shuffle(answer_option)
quizfile.write("%s.what is the capital of %s \n" %(i+1,states[i]))
for j in range(4):
quizfile.write("%s. %s\n" %('ABCD'[j],answer_option[j]))
quizfile.write('\n')
answerfile.write("%s. %s\n" %(i+1,'ABCD'[answer_option.index(correct_answer)]))
quizfile.close()
answerfile.close()
It's not the prettiest but I think it does what you're trying to do.
Extending an existing question and answer here, I am trying to extract player name and his position. The output would like:
playername, position
EJ Manuel, Quarterbacks
Tyrod Taylor, Quarterbacks
Anthony Dixon, Running backs
...
This is what I have done so far:
tree = html.fromstring(requests.get("https://en.wikipedia.org/wiki/List_of_current_AFC_team_rosters").text)
for h3 in tree.xpath("//table[#class='toccolours']//tr[2]"):
position = h3.xpath(".//b/text()")
players = h3.xpath(".//ul/li/a/text()")
print(position, players)
The above codes can deliver the following, but not in the format I need.
(['Quarterbacks', 'Running backs', 'Wide receivers', 'Tight ends', 'Offensive linemen', 'Defensive linemen', 'Linebackers', 'Defensive backs', 'Special teams', 'Reserve lists', 'Unrestricted FAs', 'Restricted FAs', 'Exclusive-Rights FAs'], ['EJ Manuel', 'Tyrod Taylor', 'Anthony Dixon', 'Jerome Felton', 'Mike Gillislee', 'LeSean McCoy', 'Karlos Williams', 'Leonard Hankerson', 'Marcus Easley', 'Marquise Goodwin', 'Percy Harvin', 'Dez Lewis', 'Walt Powell', 'Greg Salas', 'Sammy Watkins', 'Robert Woods', 'Charles Clay', 'Chris Gragg', "Nick O'Leary", 'Tyson Chandler', 'Ryan Groy', 'Seantrel Henderson', 'Cyrus Kouandjio', 'John Miller', 'Kraig Urbik', 'Eric Wood', 'T. J. Barnes', 'Marcell Dareus', 'Lavar Edwards', 'IK Enemkpali', 'Jerry Hughes', 'Kyle Williams', 'Mario Williams', 'Jerel Worthy', 'Jarius Wynn', 'Preston Brown', 'Randell Johnson', 'Manny Lawson', 'Kevin Reddick', 'Tony Steward', 'A. J. Tarpley', 'Max Valles', 'Mario Butler', 'Ronald Darby', 'Stephon Gilmore', 'Corey Graham', 'Leodis McKelvin', 'Jonathan Meeks', 'Merrill Noel', 'Nickell Robey', 'Sammy Seamster', 'Cam Thomas', 'Aaron Williams', 'Duke Williams', 'Dan Carpenter', 'Jordan Gay', 'Garrison Sanborn', 'Colton Schmidt', 'Blake Annen', 'Jarrett Boykin', 'Jonathan Dowling', 'Greg Little', 'Jacob Maxwell', 'Ronald Patrick', 'Cedric Reed', 'Cyril Richardson', 'Phillip Thomas', 'James Wilder, Jr.', 'Nigel Bradham', 'Ron Brooks', 'Alex Carrington', 'Cordy Glenn', 'Leonard Hankerson', 'Richie Incognito', 'Josh Johnson', 'Corbin Bryant', 'Stefan Charles', 'MarQueis Gray', 'Chris Hogan', 'Jordan Mills', 'Ty Powell', 'Bacarri Rambo', 'Cierre Wood'])
(['Quarterbacks', 'Running backs', 'Wide receivers', 'Tight ends', 'Offensive linemen', 'Defensive linemen', 'Linebackers', 'Defensive backs', 'Special teams', 'Reserve lists', 'Unrestricted FAs', 'Restricted FAs', 'Exclusive-Rights FAs'], ['Zac Dysert', 'Ryan Tannehill', 'Logan Thomas', 'Jay Ajayi', 'Jahwan Edwards', 'Damien Williams', 'Tyler Davis', 'Robert Herron', 'Greg Jennings', 'Jarvis Landry', 'DeVante Parker', 'Kenny Stills', 'Jordan Cameron', 'Dominique Jones', 'Dion Sims', 'Branden Albert', 'Jamil Douglas', "Ja'Wuan James", 'Vinston Painter', 'Mike Pouncey', 'Anthony Steen', 'Dallas Thomas', 'Billy Turner', 'Deandre Coleman', 'Quinton Coples', 'Terrence Fede', 'Dion Jordan', 'Earl Mitchell', 'Damontre Moore', 'Jordan Phillips', 'Ndamukong Suh', 'Charles Tuaau', 'Robert Thomas', 'Cameron Wake', 'Julius Warmsley', 'Jordan Williams', 'Neville Hewitt', 'Mike Hull', 'Jelani Jenkins', 'Terrell Manning', 'Chris McCain', 'Koa Misi', 'Zach Vigil', 'Walt Aikens', 'Damarr Aultman', 'Brent Grimes', 'Reshad Jones', 'Tony Lippett', 'Bobby McCain', 'Brice McCain', 'Tyler Patmon', 'Dax Swanson', 'Jamar Taylor', 'Matt Darr', 'John Denney', 'Andrew Franks', 'Louis Delmas', 'James-Michael Johnson', 'Rishard Matthews', 'Jacques McClendon', 'Lamar Miller', 'Matt Moore', 'Spencer Paysinger', 'Derrick Shelby', 'Kelvin Sheppard', 'Shelley Smith', 'Olivier Vernon', 'Michael Thomas', 'Brandon Williams', 'Shamiel Gary', 'Matt Hazel', 'Ulrick John', 'Jake Stoneburner'])
...
Any suggestions?
You can use nested loop for this task. First loop through the positions and then, for each position, loop through the corresponding players :
#loop through positions
for b in tree.xpath("//table[#class='toccolours']//tr[2]//b"):
#get current position text
position = b.xpath("text()")[0]
#get players that correspond to the current position
for a in b.xpath("following::ul[1]/li/a[not(*)]"):
#get current player text
player = a.xpath("text()")[0]
#print current position and player together
print(position, player)
Last part of the output :
.....
('Reserve lists', 'Chris Watt')
('Reserve lists', 'Eric Weddle')
('Reserve lists', 'Tourek Williams')
('Practice squad', 'Alex Bayer')
('Practice squad', 'Isaiah Burse')
('Practice squad', 'Richard Crawford')
('Practice squad', 'Ben Gardner')
('Practice squad', 'Michael Huey')
('Practice squad', 'Keith Lewis')
('Practice squad', 'Chuka Ndulue')
('Practice squad', 'Tim Semisch')
('Practice squad', 'Brad Sorensen')
('Practice squad', 'Craig Watts')
This question already has answers here:
Aligning rotated xticklabels with their respective xticks
(5 answers)
Closed 5 months ago.
I'm trying to do a bar plot for many countries and i want the names displayed a bit rotated underneath the bars.
The problem is that the spaces between the labels are irregular.
Here's the relevant code:
plt.bar(i, bar_height, align='center', label=country ,color=cm.jet(1.*counter/float( len(play_list))))
xticks_pos = scipy.arange( len( country_list)) +1
plt.xticks(xticks_pos ,country_list, rotation=45 )
Does anyone know a solution?
I think the problem is that the xtick label is aligned to the center of the text, but when it is rotated you care about the end of it. As a side note, you can use the position of the bars to select the xtick positions which better handles gaps/uneven spacing.
Here's an example that uses a web resource for list of countries (use your own if you don't trust the arbitrary resource google found for me)
import requests
import numpy as np
import matplotlib.pyplot as plt
# create sample data
# get a list of countries
website = "http://vbcity.com/cfs-filesystemfile.ashx/__key/CommunityServer.Components.PostAttachments/00.00.61.18.99/Country-List.txt"
r = requests.get(website)
many_countries = r.text.split()
# pick out a subset of them
n = 25
ind = np.random.randint(0, len(many_countries), 25)
country_list = [many_countries[i] for i in ind]
# some random heights for each of the bars.
heights = np.random.randint(3, 12, len(country_list))
# create plot
plt.figure(1)
h = plt.bar(range(len(country_list)), heights, label=country_list)
plt.subplots_adjust(bottom=0.3)
xticks_pos = [0.65*patch.get_width() + patch.get_xy()[0] for patch in h]
_ = plt.xticks(xticks_pos, country_list, ha='right', rotation=45)
and results in a bar chart whose labels are evenly spaced and rotated:
(your example doesn't give a hint as to what the colors mean so that's omitted here, but seems immaterial to the question anyway).
many_countries
Provided in case the website no longer works
many_countries = ['Abkhazia', 'Afghanistan', 'Akrotiri', 'and', 'Dhekelia', 'Aland', 'Albania', 'Algeria', 'American', 'Samoa', 'Andorra', 'Angola', 'Anguilla', 'Antigua', 'and', 'Barbuda', 'Argentina', 'Armenia', 'Aruba', 'Ascension', 'Island', 'Australia', 'Austria', 'Azerbaijan', 'Bahamas,', 'The', 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bermuda', 'Bhutan', 'Bolivia', 'Bosnia', 'and', 'Herzegovina', 'Botswana', 'Brazil', 'Brunei', 'Bulgaria', 'Burkina', 'Faso', 'Burundi', 'Cambodia', 'Cameroon', 'Canada', 'Cape', 'Verde', 'Cayman', 'Islands', 'Central', 'Africa', 'Republic', 'Chad', 'Chile', 'China', 'Christmas', 'Island', 'Cocos', '(Keeling)', 'Islands', 'Colombia', 'Comoros', 'Congo', 'Cook', 'Islands', 'Costa', 'Rica', 'Cote', "d'lvoire", 'Croatia', 'Cuba', 'Cyprus', 'Czech', 'Republic', 'Denmark', 'Djibouti', 'Dominica', 'Dominican', 'Republic', 'East', 'Timor', 'Ecuador', 'Egypt', 'El', 'Salvador', 'Equatorial', 'Guinea', 'Eritrea', 'Estonia', 'Ethiopia', 'Falkland', 'Islands', 'Faroe', 'Islands', 'Fiji', 'Finland', 'France', 'French', 'Polynesia', 'Gabon', 'Cambia,', 'The', 'Georgia', 'Germany', 'Ghana', 'Gibraltar', 'Greece', 'Greenland', 'Grenada', 'Guam', 'Guatemala', 'Guemsey', 'Guinea', 'Guinea-Bissau', 'Guyana', 'Haiti', 'Honduras', 'Hong', 'Kong', 'Hungary', 'Iceland', 'India', 'Indonesia', 'Iran', 'Iraq', 'Ireland', 'Isle', 'of', 'Man', 'Israel', 'Italy', 'Jamaica', 'Japan', 'Jersey', 'Jordan', 'Kazakhstan', 'Kenya', 'Kiribati', 'Korea,', 'N', 'Korea,', 'S', 'Kosovo', 'Kuwait', 'Kyrgyzstan', 'Laos', 'Latvia', 'Lebanon', 'Lesotho', 'Liberia', 'Libya', 'Liechtenstein', 'Lithuania', 'Luxembourg', 'Macao', 'Macedonia', 'Madagascar', 'Malawi', 'Malaysia', 'Maldives', 'Mali', 'Malta', 'Marshall', 'Islands', 'Mauritania', 'Mauritius', 'Mayotte', 'Mexico', 'Micronesia', 'Moldova', 'Monaco', 'Mongolia', 'Montenegro', 'Montserrat', 'Morocco', 'Mozambique', 'Myanmar', 'Nagorno-Karabakh', 'Namibia', 'Nauru', 'Nepal', 'Netherlands', 'Netherlands', 'Antilles', 'New', 'Caledonia', 'New', 'Zealand', 'Nicaragua', 'Niger', 'Nigeria', 'Niue', 'Norfolk', 'Island', 'Northern', 'Cyprus', 'Northern', 'Mariana', 'Islands', 'Norway', 'Oman', 'Pakistan', 'Palau', 'Palestine', 'Panama', 'Papua', 'New', 'Guinea', 'Paraguay', 'Peru', 'Philippines', 'Pitcaim', 'Islands', 'Poland', 'Portugal', 'Puerto', 'Rico', 'Qatar', 'Romania', 'Russia', 'Rwanda', 'Sahrawi', 'Arab', 'Democratic', 'Republic', 'Saint-Barthelemy', 'Saint', 'Helena', 'Saint', 'Kitts', 'and', 'Nevis', 'Saint', 'Lucia', 'Saint', 'Martin', 'Saint', 'Pierre', 'and', 'Miquelon', 'Saint', 'Vincent', 'and', 'Grenadines', 'Samos', 'San', 'Marino', 'Sao', 'Tome', 'and', 'Principe', 'Saudi', 'Arabia', 'Senegal', 'Serbia', 'Seychelles', 'Sierra', 'Leone', 'Singapore', 'Slovakia', 'Slovenia', 'Solomon', 'Islands', 'Somalia', 'Somaliland', 'South', 'Africa', 'South', 'Ossetia', 'Spain', 'Sri', 'Lanka', 'Sudan', 'Suriname', 'Svalbard', 'Swaziland', 'Sweden', 'Switzerland', 'Syria', 'Tajikistan', 'Tanzania', 'Thailand', 'Togo', 'Tokelau', 'Tonga', 'Transnistria', 'Trinidad', 'and', 'Tobago', 'Tristan', 'da', 'Cunha', 'Tunisia', 'Turkey', 'Turkmenistan', 'Turks', 'and', 'Caicos', 'Islands', 'Tuvalu', 'Uganda', 'Ukraine', 'United', 'Arab', 'Emirates', 'United', 'Kingdom', 'United', 'States', 'Uruguay', 'Uzbekistan', 'Vanuatu', 'Vatican', 'City', 'Venezuela', 'Vietnam', 'Virgin', 'Islands,', 'British', 'Virgin', 'Islands,', 'U.S.', 'Wallis', 'and', 'Futuna', 'Yemen', 'Zambia', 'Zimbabwe']
I cannot seem to print a list that's within a list. I know that it goes wrong when I repeat the for loop for key and values. I was wondering if there is a way to make so that it prints each troop name for each platoon.
import random, math
first_name = ['John', 'Clay', 'Gordy', 'Erv', 'Sebastian', 'Tilly', 'Jesse', 'Alban', 'Oliver', 'Samuel', 'Joseph', 'Gregory', 'Alair', 'Gilbert', 'Nigel', 'Gibson', 'Oliver', 'Ralph', 'Rufus', 'Garson', 'Ferrol', 'Miles', 'Chilton', 'Charles', 'Gordon', 'Edward', 'Gerald', 'Shel', 'Dean', 'Noah', 'Herbert', 'Humphrey', 'Hanley', 'Ruben', 'Gibson', 'Jonathan', 'Fisk', 'Harold', 'Cristian', 'Andy', 'Kyne', 'Garson', 'Jackson', 'Maitland', 'George', 'Ford', 'Raleigh', 'Fox', 'Forbes', 'Yeardleigh', 'Gordon', 'Francis', 'Jett', 'Fairfax', 'Ford', 'Haines', 'Benjamin', 'Samuel', 'Alban', 'Chip', 'Eric', 'Alban', 'Charles', 'Sherman', 'Harrison', 'Malcolm', 'Chilton', 'Eliah', 'Junior', 'Mark', 'Bond', 'Chick', 'Emmanuel', 'Raleigh', 'Brigham', 'Archibald', 'Gates', 'Filbert', 'Barnabas', 'Geoffrey', 'Terence', 'Stacy', 'Forbes', 'Gomer', 'Fairly', 'Archer', 'Oscar', 'William', 'Ernes', 'Chill', 'Gregory', 'Weylin', 'Holt', 'Clayland', 'Gram', 'Forbes', 'Set', 'Hartwell', 'Luke', 'Garson']
last_name = ['Mitchell', 'Martin', 'Anderson', 'Patel', 'Young', 'Jackson', 'Ward', 'Jackson', 'Patel', 'Walker', 'Lee', 'Patel', 'Johnson', 'Thomas', 'Morris', 'Watson', 'Martin', 'Roberts', 'Jones', 'Lewis', 'Morgan', 'Wood', 'Lee', 'White', 'James', 'Scott', 'Young', 'Clarke', 'Edwards', 'Smith', 'Jackson', 'Turner', 'Ward', 'Hall', 'Anderson', 'Walker', 'Scott', 'Mitchell', 'Williams', 'Young', 'Allen', 'Huges', 'Phillips', 'Robinson', 'Evans', 'Thomas', 'Taylor', 'Robinson', 'Harris', 'Ward', 'Johnson', 'Anderson', 'Scott', 'Martin', 'Allen', 'Clark', 'Jones', 'Wilson', 'Phillips', 'Lewis', 'Jones', 'Anderson', 'Wright', 'Clark', 'White', 'Lewis', 'Patel', 'Wilson', 'Wilson', 'Taylor', 'Williams', 'Turner', 'Smith', 'Davies', 'Harrison', 'Thompson', 'Anderson', 'Harris', 'Brown', 'Lewis', 'Phillips', 'Watson', 'Harrison', 'Harris', 'Wilson', 'Davies', 'Brown', 'Huges', 'Parker', 'King', 'Wright', 'Anderson', 'Anderson', 'Phillips', 'Harrison', 'Walker', 'Wood', 'Young', 'Clark', 'Jones']
troops = []
temp_platoon = []
platoons = []
platoon_names = ['Alpha', 'Beta', 'Charlie', 'Delta', 'Echo', 'Foxtrot', 'Golf', 'Hotel', 'India', 'Juliet', 'Kilo', 'Lima', 'Mike', 'November', 'Oscar', 'Papa', 'Quebec', 'Romeo', 'Sierra', 'Tango', 'Uniform', 'Victor', 'Whiskey', 'X-Ray', 'Yankee', 'Zulu']
a = 0
while a < 90:
s_name = random.choice(first_name) + " " + random.choice(last_name)
s_number = 100
troops.append((s_name, s_number))
a = a + 1
platoon_number = 1
troop_number = 0
for key in troops :
troop_number = troop_number + 1
a = troops.pop(0)
temp_platoon.append((a))
if troop_number == 30:
# Platoon n is the name of platoon
# Platoon is the actual platoon
platoon_number = platoon_number + 1
platoon = platoon_names.pop(0)
platoon_n = platoon
platoon = []
for k, v in temp_platoon:
platoon.append((k, v))
print("Added {} to platoon {}. He has {} health".format(k, platoon_n, v))
platoons.append((platoon_n))
troop_number = 0
def read ():
print("Reading")
for key in platoons:
print(key)
for w in key:
print(w)
print(platoons)
read()
Also note im teaching myself python 3. I have only just started touching on classes.
I may have it wrong, but I think you might want it to look something like this:
import random
first_name = ['John', 'Clay', 'Gordy', 'Erv']
last_name = ['Mitchell', 'Martin', 'Anderson', 'Patel']
platoon_names = ['Alpha', 'Beta', 'Charlie', 'Delta']
platoons = dict()
using a list comprehension we can completely replace the while loop. every soldier is a tuple (name, health)... I presume you wanted this, but if not just remove the 100).
troops = [(random.choice(first_name) + " " + random.choice(last_name), 100) for r in range(90)]
the following helper function is lifter from here
def chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i+n]
we now populate the platoons dictionary (the key is the platoon name, while the value is a list containing the soldiers).
for number, platoon in enumerate(list(chunks(troops,3))):
platoons[platoon_names[number]] = platoon
use iteritems to iterate over a dictionary.
def read ():
print("Reading")
for platoon, troops in platoons.iteritems():
print("--------Platoon name--------")
print(platoon)
print("--------troops--------")
for (name, health) in troops:
print(name)
and this is what we get.
>>> read()
Reading
--------Platoon name--------
Alpha
--------troops--------
John Anderson
Clay Mitchell
Erv Martin
--------Platoon name--------
Beta
--------troops--------
Clay Anderson
Clay Anderson
Clay Patel
--------Platoon name--------
Delta
--------troops--------
John Anderson
Gordy Martin
John Anderson
--------Platoon name--------
Charlie
--------troops--------
Clay Mitchell
Clay Patel
Clay Patel
>>>