-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01_FormatAString.py
More file actions
81 lines (52 loc) · 1.81 KB
/
01_FormatAString.py
File metadata and controls
81 lines (52 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 1 19:38:03 2017
@author: Felix
"""
'''
Given: an array containing hashes of names
Return: a string formatted as a list of names separated by commas except for the last two names, which should be separated by an ampersand.
Example:
namelist([ {'name': 'Bart'}, {'name': 'Lisa'}, {'name': 'Maggie'} ])
# returns 'Bart, Lisa & Maggie'
namelist([ {'name': 'Bart'}, {'name': 'Lisa'} ])
# returns 'Bart & Lisa'
namelist([ {'name': 'Bart'} ])
# returns 'Bart'
namelist([])
# returns ''
'''
a = [ {'name': 'Bart'}, {'name': 'Lisa'}, {'name': 'Maggie'}, {'name': 'tom'}, {'name': 'jerry'} ]
### testing
list_of_names = []
for dicts in a:
#print ( dicts.items() )
for key, value in dicts.items():
#print (value)
#temp = [key, value]
list_of_names.append( value )
list_of_names
if len(list_of_names) == 1:
print ( list_of_names[0] )
elif len(list_of_names) == 2:
print ( list_of_names[0] + ' & ' + list_of_names[1] )
elif len(list_of_names) > 2:
for i in range(len(list_of_names)-2):
print ( list_of_names[i] + ', ' + list_of_names[-2] + ' & ' + list_of_names[-1] )
else:
print ( [] )
### function
def namelist(names):
list_of_names = []
for dicts in names:
for key, value in dicts.items():
list_of_names.append( value )
if len(list_of_names) == 1:
return ( list_of_names[0] )
elif len(list_of_names) == 2:
return ( list_of_names[0] + ' & ' + list_of_names[1] )
elif len(list_of_names) > 2:
return ( ', '.join( list_of_names[0:len(list_of_names)-2] ) + ', ' + list_of_names[-2] + ' & ' + list_of_names[-1] )
else:
return ( '' )
namelist(a)