【问题标题】:Create a function that takes each item in a list as argument iteratively创建一个函数,以迭代方式将列表中的每个项目作为参数
【发布时间】:2023-01-30 23:53:33
【问题描述】:

挑战在于使用 Python 创建一个函数,该函数接收列表的子列表并将 strip 函数迭代地应用于每个子列表。之后它用清理过的子列表重建列表

输入是列表的列表。这是一个示例:

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']]

我编写的代码仅将 tringles_new 中的一个子列表作为输入并应用 strip 函数。如何让函数自动循环遍历 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

【问题讨论】:

  • 你确定问题陈述是正确的吗?为什么要将子列表作为函数参数并希望使用相同的函数来构建完整列表?

标签: python function for-loop while-loop strip


【解决方案1】:

您需要一个为每个子列表调用 clean_one 的函数。

我根据您的 clean_one 函数的实现制作了此函数。它可以改进,但至少,我对非 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()

【讨论】:

    【解决方案2】:

    也许你需要为 j 加星

    def clean_one(i):
        clean_one_output = []
        for j in i:
            j = *j
            clean_one_output.extend(j)
        return clean_one_output
    

    或两个 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
    

    【讨论】:

      猜你喜欢
      • 2018-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-22
      • 2021-05-27
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      相关资源
      最近更新 更多