python - 组合功能

标签 python list function dictionary composition

我需要一个函数的帮助,该函数输出一个字典,其中包含 R1 和 R2 之间的组合,它的输出表示 R2 ◦ R1

到目前为止,我已经

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

此功能适用于输入

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

我需要工作的是

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

我得到的是不可散列的类型列表

任何帮助都会很棒,谢谢。

最佳答案

单独使用列表理解在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)

关于python - 组合功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69547189/

相关文章:

python - 如何使用图像每个像素的值绘制 3d 图形?

python - 如何修复 Cassandra 中的问题 "Unable to complete the operation against any hosts"?

python - 对列表字典中的值求和并计算列表中第一项的所有零值

javascript - jquery 中的目标列表项

java - 包装递归函数总是一个好的做法吗?

python - 加载在 linux 中 pickle 的数据在 mac 中失败

c# - 如何将 Array.Sort 应用于 Collection<T>?

java - 如何计算二维数组中每一列的平均值?

javascript - 将 JavaScript 函数作为参数传递

python - python内部类的目的是什么?