python - 将 list.map 应用于 python 中的两个并行列表

标签 python ironpython

我有两个并行的嵌套列表。它们的长度和子长度总是匹配的。例如:

_list1 = [[1,2,3],[1,2],[1,2,3,4]]
_list2 = [[a,b,c],[a,b],[a,b,c,d]]

现在上面的结构并不能保证。我可能会得到一个平面列表甚至更深的嵌套列表。为此,如果我想将定义应用于该列表中的每个元素,我将使用 list.map 和递归,如下所示:

def ProcessList(_func, _list):
    return map( lambda x: ProcessList(_func, x) if type(x)==list else _func(x), _list )

这样我就可以将单个定义应用于未指定的嵌套列表。我怎样才能并行执行相同的操作但两个列表?我想应用一个定义,该定义将从 _list1 中获取一个元素,并且对于 _list2 中的匹配元素,它将执行一个定义。例如:

def DoSomething(i,j);
    return str(i) + str(j)

因此,如果我将此定义并行应用于两个列表,它将返回:

_newList = [[1a,2b,3c],[1a,2b],[1a,2b,3c,4d]]

再说一遍,重点是能够对未指定的列表和嵌套列表进行操作。

最佳答案

你的意思是这样的:

>>> def ProcessList(_func, *lists):
...     return map( lambda *xs: ProcessList(_func, *xs) if all(type(x) is list for x in xs) else _func(*xs), *lists )
... 
>>> def DoSomething(*args):
...     return ''.join(map(str, args))
... 
>>> _list1 = [[1,2,3],[1,2],[1,2,3,4]]
>>> _list2 = [['a','b','c'],['a','b'],['a','b','c','d']]
>>> 
>>> print (ProcessList(DoSomething, _list1, _list2))
[['1a', '2b', '3c'], ['1a', '2b'], ['1a', '2b', '3c', '4d']]

关于python - 将 list.map 应用于 python 中的两个并行列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32230904/

相关文章:

python - IronPython 和 xml.etree.ElementTree 非法字符错误

python - 为什么 python 字符串没有 __iter__ 函数?

python - 将一层权重从一个 Huggingface BERT 模型复制到另一个模型

用于列表的 Python gcd

python - 从 Windows 窗体调用 Python 脚本

c# - 从 IronPython 调用 C# 函数

python - 将列表作为变量从 bash 脚本传递给 python 脚本

python - Celery 连接到远程服务器broker_url

c# - 嵌入式 IronPython 安全

python - 加载 NLTK 感知器标记器时出现 IOError