8. Useful tidbits (loops and strings)#
8.1. Loop odds and ends#
ziplet’s you loop through multiple lists in parallel, grouping the together the k-th elements of each loop.enumerateadds a counting variable to a loop
Let’s see.
8.1.1. Syntax#
zip
for items_a, items_b, items_c in zip(list_a, list_b, list_c):
enumerate
for k, item in enumerate(list_a):
enumerate + zip
for k, (items_a, items_b, items_c) in enumerate(zip(list_a, list_b, list_c)):
questions = ['How many planets are there?',
'What is the capital city of New Mexico?',
'Which weighs more, a pound of feathers or a pound of bricks?']
answers = ['8...RIP Pluto.',
'Sante Fe.',
'A pound is a pound. They weigh the same.']
Let’s use enumeration to number the list of questions.
k = 1
for q in questions:
print(str(k) + '. ' + q)
k+=1
1. How many planets are there?
2. What is the capital city of New Mexico?
3. Which weighs more, a pound of feathers or a pound of bricks?
for k, q in enumerate(questions, start = 1):
print(str(k) + '. ' + q)
1. How many planets are there?
2. What is the capital city of New Mexico?
3. Which weighs more, a pound of feathers or a pound of bricks?
And now, let’s make the answer key.
for counter, (q, a) in enumerate(zip(questions, answers), start = 1):
# print(str(counter) + '. ' + q)
# print('\t' + a)
print(f'{k}. {q}\n\t{a}')
3. How many planets are there?
8...RIP Pluto.
3. What is the capital city of New Mexico?
Sante Fe.
3. Which weighs more, a pound of feathers or a pound of bricks?
A pound is a pound. They weigh the same.
8.1.2. List comprehension#
mixed_numbers = [99, 2, 49, 8, 12, 24, 17, 21]
double_numbers = []
odd_numbers = []
for number in mixed_numbers:
double_numbers.append(2*number)
if number%2==1:
odd_numbers.append(number)
print(double_numbers)
print(odd_numbers)
[198, 4, 98, 16, 24, 48, 34, 42]
[99, 49, 17, 21]
double_numbers2 = [2*n for n in mixed_numbers]
odd_numbers2 = [n for n in mixed_numbers if n%2==1]
print(double_numbers2)
print(odd_numbers2)
[198, 4, 98, 16, 24, 48, 34, 42]
[99, 49, 17, 21]
8.2. Strings odds and ends#
These are a few tools for manipulating strings that may be useful. You can find more information on these tools (and many many other string tools) here.
fstrings - allows you to embed data values into strings.
f'We insert the value of a variable like this {var}'
split - split a string into a list of strings based on a separator character (by default ‘ ‘ [white space])
replace - replace an occurrence of a substring
upper, lower - returns the string with all characters in UPPERCASE or lowercase, respectively
capitalize - Capitalizes the first letter of the string
endswith, startswith - checks if the string endswith or startswith a specified substring
find, index, rindex - returns the (first, first, last) location of a substring. The difference between find() and index() is that find returns -1 if the substring is not present whereas index() triggers an error in that case.
course_dept = 'DS'
course_num = 256
enrollment = 52
ds256_string = course_dept + str(course_num) + ' has ' + str(enrollment) + ' students enrolled.'
print(ds256_string)
ds256_fstring = f'{course_dept}{course_num} has {enrollment} students enrolled.'
DS256 has 52 students enrolled.
'Prof Roth'.upper()
'PROF ROTH'
twister1 = 'How much wood would a woodchunk chunk if a woodchunk could chunk wood?'
twister2 = "I'm a mother pheasant plucker. I pluck mother pheasants. I'm the most pleasant mother pheasant plucker ever to pluck a pheasant."
twister2_words = twister2.split()
twister2_words.sort()
twister2_words
['I',
"I'm",
"I'm",
'a',
'a',
'ever',
'most',
'mother',
'mother',
'mother',
'pheasant',
'pheasant',
'pheasant.',
'pheasants.',
'pleasant',
'pluck',
'pluck',
'plucker',
'plucker.',
'the',
'to']
twister1.rindex('chunk')
59
num_roommate = [2, 1, 1, 2, 1]
type_roommate = ['parrot(s)', 'cat(s)', 'human(s)', 'dog(s)', 'jumping spider(s)']
f"Prof Roth lives with {num_roommate[0]} {type_roommate[0]} and {num_roommate[1]} {type_roommate[1]} and {num_roommate[2]} {type_roommate[2]}."
'Prof Roth lives with 2 parrot(s) and 1 cat(s) and 1 human(s).'
my_string = f'Prof Roth lives with {num_roommate[0]} {type_roommate[0]}'
for num, type in zip(num_roommate[1:], type_roommate[1:]):
my_string += f' and {num} {type}'
my_string += '.'
print(my_string)
Prof Roth lives with 2 parrot(s) and 1 cat(s) and 1 human(s) and 2 dog(s) and 1 jumping spider(s).
my_string = f'Prof Roth lives with'
for k, (num, type) in enumerate(zip(num_roommate, type_roommate)):
if k==0:
my_string += f' {num} {type}'
else:
my_string += f' and {num} {type}'
my_string += '.'
print(my_string)
Prof Roth lives with 2 parrot(s) and 1 cat(s) and 1 human(s) and 2 dog(s) and 1 jumping spider(s).
8.2.1. Practice problems#
Write the code above (about Prof Roth’s roommates) in a way that is flexible enough that were he to get more pets, he could just add them to the lists and the string would be updated without changing any other code.
hi = 'hello'
bye = 'goodbye'
hi + ' and ' + bye
'hello and goodbye'
k = 10
k +=5
k
15
Generate a directory of names and email addresses for the data science faculty listed below.
first_name = ['Eatai', 'Ryan', 'Mitch', 'Todd', 'Dan']
last_name = ['Roth', 'Johnson', 'Powers', 'Neller', 'White']
for fn, ln in zip(first_name, last_name):
email = f'{fn[0].lower()}{ln.lower()}@gettysburg.edu'
print(f'{ln}, {fn} ({email})')
Roth, Eatai (eroth@gettysburg.edu)
Johnson, Ryan (rjohnson@gettysburg.edu)
Powers, Mitch (mpowers@gettysburg.edu)
Neller, Todd (tneller@gettysburg.edu)
White, Dan (dwhite@gettysburg.edu)