The challenge is to use Python to create a function that takes in sub-lists of a list and applies the strip function to each sub-list iteratively. After that it rebuilds the list with the cleaned sub-lists
The input is a list of lists. Here is a sample:
tringles_new[:15]
[['49', 'XT', '19.0', '93 \n'],
['YTX', '124.0', '167 ', '77.0\n'],
['4 ', 'Y', '128,', '125,\n'],
['142.0', '120', '141.0\n'],
['12 ', '51.0\n'],
['0,', ' 82', '156\n'],
['82', '102.0\n'],
['94', 'YYZ', '178.0', '72\n'],
[' 120', 'YXT', '142', ' 134\n'],
['45,', '46', '79.0\n'],
[' 114', 'YT', '155.0', '168\n'],
['98,', '27,', '119.0\n'],
['61,', 'XYY', '33', '1\n'],
['ZY', '103', '123.0', '76\n'],
['YZZ', '52', ' 17', ' 92\n']]
The code I've written takes only a sub-list from tringles_new as an input and applies the strip function. How can I get the function to loop through all the sub-lists in tringles_new automatically?
def clean_one(i):
clean_one_output = []
for j in i:
j = j.strip()
clean_one_output.append(j)
return clean_one_output
CodePudding user response:
You need a function that call the clean_one
for each sublist.
I made this function based on the implementation of your clean_one function. It can be improved but at least, I kept it simple for non-pythoneers.
Original Style
def clean_many(many):
clean_many_output = []
for i in many:
clean_many_output.append(clean_one(i))
return clean_many_output
Oneliner
def better_clean_many(many):
return [[j.strip() for j in i] for i in many]
Inplace
def inplace_clean_many(many):
for i in many:
for index, j in enumerate(i):
i[index] = j.strip()
CodePudding user response:
Maybe you need a star for j
def clean_one(i):
clean_one_output = []
for j in i:
j = *j
clean_one_output.extend(j)
return clean_one_output
or two for loops
def clean_one(i):
clean_one_output = []
for j in i:
for k in j:
clean_one_output.append(k)
return clean_one_output
CodePudding user response:
Here's a function func
that takes in sublists of a list and returns the full list using closures. Not sure if this is what you want.
def outer():
full_cleaned_list = []
def inner(sublist):
cleaned_sublist = [s.strip() for s in sublist]
full_cleaned_list.append(cleaned_sublist)
return full_cleaned_list
return inner
func = outer()
result = [func(l) for l in tringles_new]