【问题标题】:Map over a multidimensional list映射多维列表
【发布时间】:2021-07-27 12:03:50
【问题描述】:

我需要一种简单的方法来跨多维嵌套列表应用函数。 我看到很多推荐列表理解或嵌套列表理解的答案,但考虑到我的列表可以有“n”个嵌套的先决条件,这个等式确实变得复杂了。

输入

x = ['apple', ['banana','blossom'], ['cherry', ['jackfruit' , 'guava']]]

def lengthy(a):
   return len(a)

预期输出

ouptut = [5, [6, 7], [6, [9, 5]]]

我的实际场景当然是比lengthy() 更广泛的功能。然而,实际用例列表可以不超过 20 个元素并且最多 5 层嵌套。所以我更喜欢不使用生成器函数的解决方案。但是,如果不可否认,请同时指定将生成器转换为范式的方法。

如果可以轻松找到解决方案,则还可以对地图的其他功能和替代方案开放答案。我很想知道是否存在任何可以解决这个问题的特殊库或内置插件。即使答案不涉及使用map 函数,也要有发言权。

【问题讨论】:

  • 你试过递归吗?
  • 我尝试过但失败了。在递归方面,我递归地遇到了失败。
  • 你能分享你的递归方法吗? (代码)

标签: python list dictionary recursion nested


【解决方案1】:

我的看法:

x = ['apple', ['banana','blossom'], ['cherry', ['jackfruit' , 'guava', ['dragonfruit', 'fruit']]]]

def lenghty(x):
    for i in range(len(x)):
        if isinstance(x[i], str):
            x[i] = len(x[i])
        else:
            lenghty(x[i])

print(x)
lenghty(x)
print(x)

输出:

['apple', ['banana', 'blossom'], ['cherry', ['jackfruit', 'guava', ['dragonfruit', 'fruit']]]]
[5, [6, 7], [6, [9, 5, [11, 5]]]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 2017-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多