Reputation: 2009
Could someone help me do two things:
Here we go:
t = ['a', 'b', ['c', 'd'], ['e'], 'f']
def capitalize_list(t):
L = []
N = []
for i in range(len(t)):
if type(t[i]) == str:
L.append(t[i].capitalize())
if type(t[i]) == list:
L.extend(t[i])
for s in L:
N.append(s.capitalize())
print N
capitalize_list(t)
This code prints:
['A', 'B', 'C', 'D', 'E', 'F']
I need it to print:
['A', 'B', ['C', 'D'], ['E'], 'F']
Upvotes: 2
Views: 720
Reputation: 9868
An alternative way of doing this recursively:
def capitalize(item):
if type(item) is str:
return item.capitalize()
if type(item) is list:
return map(capitalize, item)
You could even do
def capitalize(item):
try:
return item.capitalize()
except AttributeError:
return map(capitalize, item)
-- which would use the capitalize method for any object that has it (such as a normal or unicode string) and attempt to iterate through any object that does not.
Upvotes: 1
Reputation: 98118
You can use recursion:
def capitalize_list(t):
N = []
for i in range(len(t)):
if type(t[i]) == str:
N.append(t[i].capitalize())
if type(t[i]) == list:
N.append(capitalize_list(t[i]))
return N
Output:
['A', 'B', ['C', 'D'], ['E'], 'F']
Upvotes: 3