简体   繁体   English

组合函数

[英]Composition Function

I need help with a function that outputs a dictionary that contains the composition between R1 and R2 it's output represents R2 ◦ R1我需要一个函数的帮助,该函数输出一个字典,其中包含 R1 和 R2 之间的组合,它的输出代表 R2 ◦ R1

as of now, I have到目前为止,我有

def composition(R1,R2):
  d = {i:R2[R1[i]] for i in R1}
  print(d)

this function works inputting此功能有效输入

R1 = {1:'a',2:'b',3:'c'}
R2 = {'a':'A','b':'B','c':'C'}
output: {1: 'A', 2: 'B', 3: 'C'}

what I need to work is我需要工作的是

R1 = {1 : [2, 3], 2 : [3], 3 : [4], 4 : [1, 3]}
R2 = {1 : [3], 2 : [1, 4], 3 : [2], 4 : [1, 2]}
output should be: R2 ◦ R1 = {1 : [1, 2, 4], 2 : [2], 3 : [1, 2], 4 : [2, 3]}

what I get is unhashable type list我得到的是不可散列的类型列表

Any help would be great, Thank You.任何帮助都会很棒,谢谢。

Since both the values of R1 and R2 are lists, you need nested comprehensions to get all the mapped elements in a flattened result for each key:由于 R1 和 R2 的值都是列表,因此您需要嵌套推导来获取每个键的扁平结果中的所有映射元素:

R1 = {1 : [2, 3], 2 : [3], 3 : [4], 4 : [1, 3]}
R2 = {1 : [3], 2 : [1, 4], 3 : [2], 4 : [1, 2]}


output = {k1:[n2 for n1 in v1 for n2 in R2[n1]] for k1,v1 in R1.items()}

print(output)
{1: [1, 4, 2], 2: [2], 3: [1, 2], 4: [3, 2]}

It's a little convoluted to write in Python using list comprehension alone (maybe readability can be a bit improved by using functools.reduce to collapse the sublists), but it should be something like this:单独使用列表推导在 Python 中编写有点令人费解(也许可以通过使用functools.reduce折叠子列表来提高可读性),但它应该是这样的:

def composition(R1, R2):
  d = {
      i: [
          val
          for sublist in [R2[j] for j in R1[i]]
          for val in sublist
      ]
      for i in R1
  }

  print(d)

Here is a generic solution working in both cases.这是适用于两种情况的通用解决方案。

In summary, check if the value is a non-string iterable and compose all elements, else just compose the value.总之,检查该值是否为非字符串可迭代并组合所有元素,否则仅组合该值。

from collections.abc import Iterable
from itertools import chain

def composition(R1, R2):
    return {k1: list(chain(*[R2[e] for e in v1]))
            if isinstance(v1, Iterable)
            and not isinstance(v1, str)
            else v1
            for k1,v1 in R1.items()}

Example 1:示例 1:

>>> R1 = {1:'a',2:'b',3:'c'}
>>> R2 = {'a':'A','b':'B','c':'C'}
>>> composition(R1, R2)
{1: 'a', 2: 'b', 3: 'c'}

Example 2:示例 2:

>>> R1 = {1 : [2, 3], 2 : [3], 3 : [4], 4 : [1, 3]}
>>> R2 = {1 : [3], 2 : [1, 4], 3 : [2], 4 : [1, 2]}
>>> composition(R1, R2)
{1: [1, 4, 2], 2: [2], 3: [1, 2], 4: [3, 2]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM