Trying to create a function to filter out 'University of' from a list of university data in order to sort them alphabetically. This is the code I have so far:
def filter_list(uni):
for u in uni:
for n in u:
if n.startswith('University of the '):
n = n[18:] ' University'
elif n.startswith('University of '):
n = n[14:] ' University'
return uni
Expected output:
('Buckinghamshire New University', '78%', '39%', '82%', '0%', '0%', '52%'), ('Middlesex University', '82%', '48%', '80%', '57%', '75%', '54%'), ('City, University of London', '83%', '51%', '77%', '69%', '63%', '59%'), ('Goldsmiths, University of London', '85%', '54%', '77%', '70%', '100%', '61%'), ('Bedfordshire University', '81%', '42%', '77%', '58%', '57%', '61%'), ('Bolton University', '81%', '48%', '85%', '0%', '0%', '63%')...
Current output:
('Buckinghamshire New University', '78%', '39%', '82%', '0%', '0%', '52%'), ('Middlesex University', '82%', '48%', '80%', '57%', '75%', '54%'), ('City, University of London', '83%', '51%', '77%', '69%', '63%', '59%'), ('Goldsmiths, University of London', '85%', '54%', '77%', '70%', '100%', '61%'), ('University of Bedfordshire', '81%', '42%', '77%', '58%', '57%', '61%'), ('University of Bolton', '81%', '48%', '85%', '0%', '0%', '63%')...
The code to change the name of the strings works, it's just the matter of modifying the actual strings in the lists. Anyone know how to do this?
CodePudding user response:
You assign your value to n
, but you never use n
any further. Changing n
does not change the value in the tuple in the list.
Instead you can create a new list and append each university to that with a new list containing the filtered values for each university. I've also taken the liberty to use more descriptive variable names.
def filter_university_list(universities):
filtered_universities = []
for university in universities:
current_university = []
for field in university:
if field.startswith('University of the '):
field = field[18:] ' University'
elif field.startswith('University of '):
field = field[14:] ' University'
current_university.append(field)
filtered_universities.append(current_university)
return filtered_universities