python - 对多级列表中的每一项执行操作

标签 python list

假设我有一个这样的列表:

li = ['0', ['1', '2'], ['3', ['4', '5'], '6', ['7'], '8'], '9']

如何以 Pythonic 方式对列表中的所有元素应用一个函数(例如 int)?
示例:

>>> func_on_all(li, int)
[0, [1, 2], [3, [4, 5], 6, [7], 8], 9]

最佳答案

你可以使用这个函数:

def to_int(lst):
    for i in lst:
        if isinstance(i, list):
            yield list(to_int(i))
        else:
            yield int(i)

这是一个测试运行:

>>> li = ['0', ['1', '2'], ['3', ['4', '5'], '6', ['7'], '8'], '9']
>>> list(to_int(li))
[0, [1, 2], [3, [4, 5], 6, [7], 8], 9]

请注意,这仅适用于嵌套列表,并且只能执行 int 功能。我们可以像这样使函数更通用:

def deep_map(lst, f=int):  # the parameter `f` is the function
    for i in lst:
        if isinstance(i, collections.Iterable) and not isinstance(i, str):
            yield list(deep_map(i, f))
        else:
            yield f(i)

这将允许我们使用列表以外的嵌套集合(例如元组),并且我们可以指定我们自己的函数来调用列表。

关于python - 对多级列表中的每一项执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15807855/

相关文章:

python - 从多个文件的行创建生成器

R:检查向量的多个元素是否出现在字符串向量中

python - 如何在 Python 中拆分嵌套列表中的字符串?

ruby - 如何从 Ruby 可枚举列表中获取列表?

python - 读取文本文件、操作字符串并以特定格式导出 csv

python 语法中的 Java 主类

python - pydrake : How do I identify slow Python LeafSystem's (to possibly rewrite in C++)?

python - Matplotlib - 只显示一个数字

python - 如何在 Tensorflow 中生成/读取 CTC 损失的稀疏序列标签?

c# - 使用 System.Net.Mail.SmtpClient 将电子邮件发送到通讯组列表