[英]Create a function that takes each item in a list as argument iteratively
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.挑战在于使用 Python 创建一个 function,它接受列表的子列表并将条带 function 迭代地应用于每个子列表。 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?我编写的代码仅将 tringles_new 中的子列表作为输入并应用条带 function。如何让 function 自动循环遍历 tringles_new 中的所有子列表?
def clean_one(i):
clean_one_output = []
for j in i:
j = j.strip()
clean_one_output.append(j)
return clean_one_output
You need a function that call the clean_one
for each sublist.您需要一个 function 来为每个子列表调用clean_one
。
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.我根据您的 clean_one function 的实现制作了这个 function。它可以改进,但至少,我对非 python 用户保持简单。
def clean_many(many):
clean_many_output = []
for i in many:
clean_many_output.append(clean_one(i))
return clean_many_output
def better_clean_many(many):
return [[j.strip() for j in i] for i in many]
def inplace_clean_many(many):
for i in many:
for index, j in enumerate(i):
i[index] = j.strip()
Maybe you need a star for j也许你需要为 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或两个 for 循环
def clean_one(i):
clean_one_output = []
for j in i:
for k in j:
clean_one_output.append(k)
return clean_one_output
Here's a function func
that takes in sublists of a list and returns the full list using closures.这是一个 function func
,它接收列表的子列表并使用闭包返回完整列表。 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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.